Stripe Address Element Add Asterisks To Required

I’m using the AddressElement from Stripe in React/Next.

How can I customize the label for the input?

For example, if I want a * to show up for if it’s required, how would I do that?

I tried looking at the Appearance API and tried setting some rules, but there’s no content available for their CSS rules.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connection 27 to localhost:27017 timed out]

I’m trying to create some documents using mongoose’s insertMany, but it fails when connecting to Mongo host.

My code is below:

const { current, last } = getDates();
const currentData = await getProofsOfDeliveryData(current);
const lastData = await getProofsOfDeliveryData(last);
const data = [...currentData, ...lastData];
await ProofOfDeliveryProd.deleteMany();
await ProofOfDeliveryProd.insertMany(data);

I expect to insert about 12k documents

Add aria label to an image using javascript

I am using a theme builder for WordPress and I’ve created some panels with an image and a bit of text in each. However, using the theme’s builder tools does not allow me to add aria labels to the images. So I’m trying to add aria labels to the images using javascript, but I just can’t seem to get this figured out. Can anyone help with this?

Here’s my HTML:

<div  class="module module-link-block tb_c1o1565 icon-center solid licences-permits" data-lazy="1"><a href="#" title="Licences &amp; Permits" class="tb_link_block_container ui tb_default_color"><img loading="lazy" width="66" height="66" decoding="async" class="tf_vmiddle tf_box tb_link_block_img" src="https://xxxxx.xxxxx.xxxxxx.net/wp-content/uploads/2024/04/licence-1.svg"><div class="tf-lb-content"><div class="tb_link_block_heading">Licences & Permits</div><div class="tb_link_block_blurb">Browse Licenses & Permits</div></div></a></div>

And here’s the javascript I’ve got so far… but it isn’t adding the aria label to the image img scr.

jQuery(function($) { 
jQuery('.licences-permits').attr('aria-label','Licences & Permits'); 
 }); 
</script>```

Passing form inputted string to an entity’s attribute

I have a medusajs website and backend. I am trying to add a metadata entity to the cart entity, when the customer is checking out their cart they are supposed to input a string which gets saved to the cart object which then gets created into an order and passed to my backend. Per their documentation it should be done like this. I am fairly new to web development and having trouble completing such an easy task.

Here is my attempt at doing this, it seems like the value in the Input component gives me an error because you can’t set it as a key value pair, it has to be a string but my other attempts to fix this have not been so good either

"use client"

import { Heading, Text, clx } from "@medusajs/ui"
import React, { useState, useEffect, useMemo } from "react"
import { useSearchParams } from "next/navigation"
import { Cart } from "@medusajs/medusa"
import Input from "@modules/common/components/input"
const CustomString = ({
cart,

}: {
 cart: Omit<Cart, "refundable_amount" | "refunded_total"> 

}) => {

const [formData, setFormData] = useState({
  //I have tried rewriting this in a couple different ways
    "cart.metadata": {"customString" : cart?.metadata || ""},
})

const searchParams = useSearchParams()
const isOpen = searchParams.get("step") === "review"

const previousStepsCompleted =
 cart.shipping_address &&
 cart.shipping_methods.length > 0 &&
 cart.payment_session

useEffect(() => {
    setFormData({
     "cart.metadata": {"customString" : cart?.metadata || ""},
  
    })
  }, [cart?.metadata])

const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLInputElement | HTMLSelectElement
    >
  ) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    })
  }
return (
 <div>
  {isOpen && previousStepsCompleted && (
    <>
      <div className="flex items-start gap-x-1 w-full mb-6">

      <Input
      label="User Input"
      name="cart.metadata"
      maxLength={11}
      value= { cart?.metadata} //I get errors here
      onChange={handleChange}

          />

      </div>
    </>
  )}
</div>
)
}

export default CustomString

Any suggestions?

Find the percentage of the figure area covered by own drawing

There is simple shape(red triangle) and complex(black “U shape”).
I draw blue shape by mouse and willing to find: percentage of the figure been covered by drawing(blue color).

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="800" height="600"></canvas>
    <script>
      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      const radius = 15;

      const random_shape = [
        { x: 20, y: 20, width: 20, height: 100 },
        { x: 60, y: 20, width: 20, height: 100 },
        { x: 20, y: 120, width: 60, height: 20 },
      ];

      const triangle = [
        { x: 200, y: 400 },
        { x: 400, y: 200 },
        { x: 600, y: 400 },
      ];

      let isDrawing = false;
      let lastX = 0;
      let lastY = 0;
      let pixelsInsideFigure = 0;

      function draw_random_shape() {
        for (let i = 0; i < random_shape.length; i++) {
          ctx.fillStyle = "black";
          ctx.fillRect(
            random_shape[i].x,
            random_shape[i].y,
            random_shape[i].width,
            random_shape[i].height
          );
        }
      }

      function draw_triangle() {
        ctx.beginPath();
        ctx.moveTo(triangle[0].x, triangle[0].y);
        for (let i = 1; i < triangle.length; i++) {
          ctx.lineTo(triangle[i].x, triangle[i].y);
        }
        ctx.closePath();
        ctx.fillStyle = "red";
        ctx.fill();
      }

      function handleMouseDown(e) {
        isDrawing = true;
        [lastX, lastY] = [e.offsetX, e.offsetY];
        if (pointInShape({ x: lastX, y: lastY }, random_shape)) {
          pixelsInsideFigure++;
        }
      }

      function handleMouseMove(e) {
        if (!isDrawing) return;
        ctx.strokeStyle = "blue";
        ctx.lineJoin = "round";
        ctx.lineCap = "round";
        ctx.lineWidth = radius;
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        [lastX, lastY] = [e.offsetX, e.offsetY];
        if (pointInShape({ x: lastX, y: lastY }, random_shape)) {
          pixelsInsideFigure++;
        }
      }

      function handleMouseUp() {
        isDrawing = false;
        calculatePercentage();
        pixelsInsideFigure = 0;
      }

      function clearUserInput() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        draw_triangle();
        draw_random_shape();
      }

      function calculatePercentage() {
        const coveredArea = calculateCoveredArea(
          { x: lastX, y: lastY },
          radius
        );
        const totalArea = Math.PI * Math.pow(radius, 2);
        const coveragePercentage = (coveredArea / totalArea) * 100;

        alert(`Area Coverage Percentage: ${coveragePercentage.toFixed(2)}%`);
        clearUserInput();
      }

      function pointInShape(point, vertices) {
        let inside = false;
        const x = point.x;
        const y = point.y;
        for (let i = 0, j = vertices.length - 1; i < vertices.length; j = i++) {
          const xi = vertices[i].x;
          const yi = vertices[i].y;
          const xj = vertices[j].x;
          const yj = vertices[j].y;
          const intersect =
            yi > y != yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
          if (intersect) inside = !inside;
        }
        return inside;
      }

      function calculateCoveredArea(point, radius) {
        let coveredArea = 0;
        const centerX = point.x;
        const centerY = point.y;

        for (let x = centerX - radius; x <= centerX + radius; x++) {
          for (let y = centerY - radius; y <= centerY + radius; y++) {
            const distance = Math.sqrt(
              Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2)
            );
            if (distance <= radius) {
              if (pointInShape({ x: x, y: y }, random_shape)) {
                console.log("INSIDE RANDOM SHAPE");
                coveredArea++;
              }
              if (pointInShape({ x: x, y: y }, triangle)) {
                console.log("INSIDE Triangle");
                coveredArea++;
              }
            }
          }
        }

        return coveredArea;
      }

      function calculateArea(vertices) {
        let area = 0;
        for (let i = 0, j = vertices.length - 1; i < vertices.length; j = i++) {
          area +=
            (vertices[j].x + vertices[i].x) * (vertices[j].y - vertices[i].y);
        }
        return Math.abs(area / 2);
      }

      function init() {
        draw_triangle();
        draw_random_shape();

        canvas.addEventListener("mousedown", handleMouseDown);
        canvas.addEventListener("mousemove", handleMouseMove);
        canvas.addEventListener("mouseup", handleMouseUp);
      }

      init();
    </script>
  </body>
</html>

P.S. As reference in Harry Potter 1 I have to lead a wand to fit the shape. To pass the skill you have to properly cover the area.
enter image description here

In provided case I am expecting to get around 60-70%(top left corner).
enter image description here

Searching the internet, asking “bots”, did math adjustments – did not help.
Expecting: proper way to calculate and find the area percentage.

How can i get github to show my second html? keep getting 404 error

when i host the site locally it calls on the second page fine but when i host the site through github it keeps returning a 404 error saying my site is not found. can anyone help? https://github.com/NCOBBagg/FES__Javascript–Project

ive tried multiple different solutions ive seen on community posts and even tried to host to netlify to remedy the situation, while netlify will navigate to the second html page it wont call on my api. so either way im stuck.

I can’t add my custom product to my woocommerce cart

I am working on a custom plug-in that creates a product type – “roller blind dimensions” and custom variants of this product. Then, in the frontend, the code calculates the price based on the dimensions entered by the customer and those available in the backend. Unfortunately, I can’t manage to add the product to the cart. The product is added but nothing appears in the cart. I can’t find an error, what is wrong in the code, that this product, its variant and dimensions entered by the customer are not added correctly to the woocommerce cart?

// Możesz zdefiniować klasę produktu dla niestandardowego typu produktu
function register_custom_product_type() {
    class WC_Product_Custom_Roll_Dimensions extends WC_Product {
        // Explicitly declare the product_type property
        public $product_type;

        public function __construct( $product ) {
            $this->product_type = 'custom_roll_dimensions';
            parent::__construct( $product );
        }

        // Additional methods specific to this product type
    }

    // Add the custom product type to WooCommerce
    add_filter('product_type_selector', function( $types ){
        $types['custom_roll_dimensions'] = 'Wymiary Rolet';
        return $types;
    });
}

add_action('init', 'register_custom_product_type');

class CustomVariantsManager {


    public function __construct() {
       

        
        add_action('admin_enqueue_scripts', array($this, 'enqueueStyles'));
         add_action('admin_enqueue_scripts', array($this, 'enqueue_and_localize_scripts'));
         add_action('add_meta_boxes', array($this, 'addCustomVariantsMetabox'));

        add_action('save_post', array($this, 'saveCustomVariants'), 10, 2);
        add_action('wp_ajax_custom_variants_pagination', array($this, 'customVariantsPagination'));
        add_action('wp_ajax_nopriv_custom_variants_pagination', array($this, 'customVariantsPagination'));
        add_action('wp_ajax_remove_custom_variant', array($this, 'removeCustomVariantCallback'));
        add_action('wp_ajax_add_custom_variant', array($this, 'addCustomVariantCallback'));
        // Include the kalkulator.php file
        include_once(plugin_dir_path(__FILE__) . 'Kalkulator.php');

    }

    // Enqueue styles for the admin area
    public function enqueueStyles() {
        wp_enqueue_style('moj-wtyczka-styl', plugins_url('css/moj-wtyczka-styl.css', __FILE__));
    }
        
    
    public function enqueue_and_localize_scripts(){
        // Enqueue your JavaScript file
        wp_enqueue_script('custom-variants-scripts', plugin_dir_url(__FILE__) . 'JS/custom-variants-scripts.js', array('jquery'), '1.0', true);

         // Localize the script with necessary data
         wp_localize_script('custom-variants-scripts', 'ajax_object', array(
          'post_id' => get_the_ID(),
            'ajax_url' => admin_url('admin-ajax.php'), // Make sure this points to admin-ajax.php
        ));
         wp_localize_script('custom-variants-scripts', 'custom_script_vars', array(
            'post_id' => get_the_ID(), // Notice the comma here
         ));
    }

    


    
 // Add the custom variants metabox
public function addCustomVariantsMetabox() {
        add_meta_box(
            'custom_variants_metabox_id',   // Unique ID
            'Warianty Produktu',            // Box title
            array($this, 'customVariantsMetaboxHtml'), // Content callback, must be of type callable
             ['product', 'custom_roll_dimensions'], // Dodano wsparcie dla nowego typu produktu
    'normal'
        );
    }
    public function customVariantsMetaboxHtml($post) {
        wp_nonce_field(plugin_basename(__FILE__), 'custom_variants_nonce');
// Retrieve existing variants if any
    $variants = get_post_meta($post->ID, 'custom_variants', true);
    if (!is_array($variants)) {
        $variants = []; // Initialize as an empty array if not an array
    }
    // Retrieve shipping classes
    $shipping_classes = get_terms('product_shipping_class', array('hide_empty' => false));

    echo '<div id="custom_variants_containers">';
    echo '<button id="add_variant" type="button">Dodaj Nowy Wariant</button>';
    echo '<button id="remove_all_variants" type="button">Usuń Wszystkie Warianty</button>';

  $totalVariants = count($variants);
    echo '<div id="total_variants">Wszystkie: ' . $totalVariants . '</div>';
    echo '<div id="custom_variants_container">';
    if ($variants) {
  foreach ($variants as $index => $variant) {
            echo '<div class="variant">';
            $dimensions = esc_attr($variant['width']) . 'x' . esc_attr($variant['height']);
        echo '<style>';
            echo '[id^="variant_dimensions_"] {';
            echo '    margin-left: 10px;';
            echo '}';
            echo '</style>';
            echo '<div id="variant_dimensionsss">';
                echo '<div id="variant_dimensionss" style="display: flex; align-items: center;">';
            echo '<span>ID wariantu: ' . esc_html($variant['id']) . '</span>';  // Dodanie wyświetlania ID wariantu
            echo '<div id="variant_dimensions_' . $index . '" style="display: flex; align-items: center;">';
                    echo '<label="variant_dimensions_' . $index . '">Wymiary:</label>';
                    echo '<span id="variant_dimensions_' . $index . '">' . $dimensions . '</span>';
    echo '</div>';
                echo '</div>';
            echo '<div>';
            echo '<button class="remove_variant" type="button" data-index="' . $index . '">Usuń Wariant</button>';
            echo '<button class="rozwin_variant" type="button" data-index="' . $index . '">Rozwiń</button>';
            echo '</div>';
            echo '</div>';
            echo '<div id="custom_variants_containerx">';
            echo '<div id="custom_variants_container1" style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">';
            echo '<div>';
            echo '<label for="variant_width_' . $index . '">Szerokość</label>';
            echo '<input type="text" id="variant_width_' . $index . '" name="variants[' . $index . '][width]" value="' . esc_attr($variant['width']) . '" />';
            echo '</div>';
            echo '<div>';
            echo '<label for="variant_height_' . $index . '">Wysokość</label>';
            echo '<input type="text" id="variant_height_' . $index . '" name="variants[' . $index . '][height]" value="' . esc_attr($variant['height']) . '" />';
            echo '</div>';
            echo '<div>';
            echo '<label for="variant_sku_' . $index . '">SKU</label>';
            echo '<input type="text" id="variant_sku_' . $index . '" name="variants[' . $index . '][sku]" value="' . esc_attr($variant['sku']) . '" />';
            echo '</div>';
            echo '</div>';
            echo '<div id="custom_variants_container2" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">';
            echo '<div>';
            echo '<label for="variant_regular_price_' . $index . '">Cena Regularna</label>';
            echo '<input type="text" id="variant_regular_price_' . $index . '" name="variants[' . $index . '][regular_price]" value="' . esc_attr($variant['regular_price']) . '" size="50" />';
            echo '</div>';
            echo '<div>';
            echo '<label for="variant_sale_price_' . $index . '">Cena Promocyjna</label>';
            echo '<input type="text" id="variant_sale_price_' . $index . '" name="variants[' . $index . '][sale_price]" value="' . esc_attr($variant['sale_price']) . '" size="50" />';
            echo '</div>';
            echo '</div>';
            echo '<div id="custom_variants_container3" style="display: grid; grid-template-columns: repeat(1, 1fr); gap: 0px;">';
            echo '<label for="variant_weight_' . $index . '">Waga</label>';
            echo '<input type="text" id="variant_weight_' . $index . '" name="variants[' . $index . '][weight]" value="' . esc_attr($variant['weight']) . '" size="25" />';
            echo '</div>';
echo '<div>';
echo '<label for="variant_stock_status_' . $index . '">Stan magazynowy:</label>';
echo '<select id="variant_stock_status_' . $index . '" name="variants[' . $index . '][stock_status]">';
echo '<option value="instock"' . (isset($variant['stock_status']) && $variant['stock_status'] === 'instock' ? ' selected' : '') . '>Na stanie</option>';
echo '<option value="outofstock"' . (isset($variant['stock_status']) && $variant['stock_status'] === 'outofstock' ? ' selected' : '') . '>Brak na stanie</option>';
echo '</select>';
echo '</div>';


            echo '<div id="custom_variants_container4" style="display: grid; grid-template-columns: repeat(1, 1fr); gap: px;">';
            // Klasa Wysyłkowa
            echo '<label for="variant_shipping_class_' . $index . '">Klasa Wysyłkowa</label>';
            echo '<select name="variants[' . $index . '][shipping_class]" id="variant_shipping_class_' . $index . '" class="postform">';
            echo '<option value="-1"' . (!isset($variant['shipping_class']) || $variant['shipping_class'] == '-1' ? ' selected="selected"' : '') . '>Taka sama jak nadrzędny</option>';

            foreach ($shipping_classes as $class) {
                $selected = (isset($variant['shipping_class']) && $variant['shipping_class'] == $class->slug) ? ' selected="selected"' : '';
                echo '<option value="' . esc_attr($class->slug) . '"' . $selected . '>' . esc_html($class->name) . '</option>';
            }
            echo '</select>';
            echo '</div>';
          echo '</div>';
            echo '</div>';
        }
    }
echo '<div id="pagination-container"></div>';
echo '</div>'; // Closing tag for "custom_variants_container"
// Dodanie przycisku i pola do przesyłania pliku CSV
echo '<div id="import" class="import-container">';
  echo '<label for="csv_variants">Importuj warianty z pliku CSV:</label>';
    echo '<input type="file" id="csv_variants" name="csv_variants" accept=".csv">';
    echo '<button id="import_csv_btn" class="button_import" onclick="importCsvVariants()">Importuj</button>';
echo '</div>';
}   
    
public function saveCustomVariants($post_id, $post) {
    // Check permissions and security
    if (!current_user_can('edit_post', $post_id) || 
        (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || 
        isset($_REQUEST['bulk_edit']) ||
        (isset($_POST['importing_csv']) && $_POST['importing_csv'] === 'yes') ||
        (!isset($_POST['custom_variants_nonce']) || !wp_verify_nonce($_POST['custom_variants_nonce'], plugin_basename(__FILE__)))) {
        return $post_id;
    }

    // Handle CSV Import
    $custom_variants = get_post_meta($post_id, 'custom_variants', true) ?: [];
    if (isset($_FILES['csv_variants']) && $_FILES['csv_variants']['error'] == UPLOAD_ERR_OK) {
        $file = fopen($_FILES['csv_variants']['tmp_name'], 'r');
        if ($file) {
            fgetcsv($file); // Skip header
            while (($data = fgetcsv($file)) !== FALSE) {
                if (count($data) >= 3) {
                    $new_variant = [
                        'id' => uniqid(), // Dodajemy unikalne ID
                        'width' => sanitize_text_field($data[0]),
                        'height' => sanitize_text_field($data[1]),
                        'regular_price' => sanitize_text_field($data[2]),
                        'sale_price' => '',
                        'weight' => '',
                        'shipping_class' => '-1',
                        'stock_status' => $posted_variant['stock_status'] ?? 'instock' // Ustawienie domyślne na 'Na stanie'
                    ];

                    // Check for duplicates
                    $found = false;
                    foreach ($custom_variants as &$variant) {
                        if ($variant['width'] == $new_variant['width'] && $variant['height'] == $new_variant['height']) {
                            $variant = $new_variant; // Update existing variant
                            $found = true;
                            break;
                        }
                    }
                    if (!$found) {
                        $custom_variants[] = $new_variant; // Add new variant
                    }
                }
            }
            fclose($file);
        }
    }
// Initialize an empty array for custom variants
$custom_variants = [];

// Save Custom Variants from Post Data
if (isset($_POST['variants']) && !empty($_POST['variants'])) {
    $custom_variants = []; // Resetujemy tablicę wariantów przed zapisaniem nowych danych
    foreach ($_POST['variants'] as $posted_variant) {
          // Reset the duplicate flag for each variant
        $duplicate_found = false;
        $new_variant = [
            'id' => $posted_variant['id'] ?? uniqid(),
            'width' => sanitize_text_field($posted_variant['width']),
            'height' => sanitize_text_field($posted_variant['height']),
            'regular_price' => floatval($posted_variant['regular_price']),
            'sale_price' => isset($posted_variant['sale_price']) ? floatval($posted_variant['sale_price']) : '',
            'weight' => isset($posted_variant['weight']) ? sanitize_text_field($posted_variant['weight']) : '',
            'sku' => isset($posted_variant['sku']) ? sanitize_text_field($posted_variant['sku']) : '',
            'shipping_class' => isset($posted_variant['shipping_class']) ? sanitize_text_field($posted_variant['shipping_class']) : '',
            'stock_status' => $posted_variant['stock_status'] ?? 'instock' // Ustawienie domyślne na 'Na stanie'
        ];

        // Check for duplicates
       foreach ($custom_variants as &$variant) {
                if ($variant['width'] == $new_variant['width'] && $variant['height'] == $new_variant['height']) {
                    $duplicate_found = true;
                    break;
                }
            }

            if (!$duplicate_found) {
                $custom_variants[] = $new_variant; // Add new variant   
            }
            }
} else {
    // If variants are not set or empty, it means all have been removed
    delete_post_meta($post_id, 'custom_variants'); // Alternatively, use update_post_meta($post_id, 'custom_variants', []);
    return; // Exit the function
}
    update_post_meta($post_id, 'custom_variants', $custom_variants);
 // Zaktualizuj metadane produktu na podstawie wariantów
    if (!empty($custom_variants)) {
        $min_price = PHP_INT_MAX;
        $max_price = PHP_INT_MIN;
        $stock_status = 'instock'; // Domyślnie produkt jest dostępny

        foreach ($custom_variants as $variant) {
            $regular_price = isset($variant['regular_price']) ? floatval($variant['regular_price']) : PHP_INT_MAX;
            $sale_price = isset($variant['sale_price']) && floatval($variant['sale_price']) > 0 ? floatval($variant['sale_price']) : PHP_INT_MAX;
            $current_price = min($regular_price, $sale_price);

            $min_price = min($min_price, $current_price);
            $max_price = max($max_price, $current_price);

            if (isset($variant['stock']) && intval($variant['stock']) <= 0) {
                $stock_status = 'outofstock';
            }
        }

        update_post_meta($post_id, '_min_variation_price', $min_price);
        update_post_meta($post_id, '_max_variation_price', $max_price);
        update_post_meta($post_id, '_stock_status', $stock_status);

        // Usuń wartość _price, aby nie wpływać na inne procesy WooCommerce
        delete_post_meta($post_id, '_price');
    } else {
        // Usuń metadane, jeśli nie ma wariantów
        delete_post_meta($post_id, '_min_variation_price');
        delete_post_meta($post_id, '_max_variation_price');
        delete_post_meta($post_id, '_stock_status');
        delete_post_meta($post_id, '_price');
    }
         // Zaktualizuj metadane produktu na podstawie wariantów
    $stock_status = 'instock'; // Domyślnie produkt jest dostępny

    foreach ($custom_variants as $variant) {
        if (isset($variant['stock']) && $variant['stock'] <= 0) {
            $stock_status = 'outofstock';
            break;
        }
    }

    update_post_meta($post_id, '_stock_status', $stock_status);
    }
    
    
public function removeCustomVariantCallback() {
    $post_id = $_POST['post_id'];
    $indexToRemove = $_POST['index'];

    $custom_variants = get_post_meta($post_id, 'custom_variants', true);

    if(isset($custom_variants[$indexToRemove])) {
        unset($custom_variants[$indexToRemove]);
        update_post_meta($post_id, 'custom_variants', array_values($custom_variants)); // Re-index the array
        echo 'success';
    } else {
        echo 'error';
    }

    wp_die();
}

public function addCustomVariantCallback() {
    $post_id = $_POST['post_id'];
    $newVariant = $_POST['new_variant'];

    $custom_variants = get_post_meta($post_id, 'custom_variants', true);

    // Check if a variant with the same price, width, and height already exists
    foreach ($custom_variants as $variant) {
        if (
            $variant['width'] == $newVariant['width'] &&
            $variant['height'] == $newVariant['height']) {
            echo json_encode(['error' => 'Variant with same price, width, and height already exists']);
            wp_die();
        }
    }

    // Add the new variant to the beginning of the array
    array_unshift($custom_variants, $newVariant);

    // Update the post meta with the new array of variants
    update_post_meta($post_id, 'custom_variants', $custom_variants);

    echo 'success';

    wp_die();
}
     // Dodaj funkcję obsługującą paginację AJAX
    public function customVariantsPagination() {
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $itemsPerPage = 1; // Ilość elementów do wyświetlenia na jednej stronie
        $startIndex = ($page - 1) * $itemsPerPage;

    // Wyślij dane jako JSON
        echo json_encode($variants); // $variants to tablica z wariantami na danej stronie
        wp_die();
    }   
}



 
 // Instantiate the class
$customVariantsManager = new CustomVariantsManager();


add_filter('woocommerce_get_price_html', 'display_price_range_on_product_page', 10, 2);

function display_price_range_on_product_page($price, $product) {
    // Sprawdzenie, czy produkt jest typu 'variable' lub 'custom_roll_dimensions'
    if ($product->is_type('variable') || $product->is_type('custom_roll_dimensions')) {
        $min_price = $product->get_meta('_min_variation_price', true);
        $max_price = $product->get_meta('_max_variation_price', true);

        // Zwracanie zakresu cen, jeśli istnieje różnica pomiędzy minimalną a maksymalną ceną
        if (!empty($min_price) && !empty($max_price) && $min_price != $max_price) {
            return wc_price($min_price) . ' – ' . wc_price($max_price);
        } else if (!empty($min_price)) {
            // Zwracanie tylko minimalnej ceny, jeśli maksymalna jest pusta lub równa minimalnej
            return wc_price($min_price);
        }
    }
    // Dla innych typów produktów, zwracanie oryginalnej ceny
    return $price;
}

Below I present the code that calculates the product price and “adds” the supposedly calculated variant to the WooCommerce cart. However, nothing appears in the cart and it is still empty.


function get_dimension_ranges() {
    $product_title = isset($_POST['product_title']) ? sanitize_text_field($_POST['product_title']) : '';

    // Wyszukiwanie posta (produktu) na podstawie tytułu
    $query = new WP_Query([
        'post_type' => 'product',
        'title' => $product_title
    ]);

    if ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();

        $min_width = PHP_FLOAT_MAX;
        $max_width = PHP_FLOAT_MIN;
        $min_height = PHP_FLOAT_MAX;
        $max_height = PHP_FLOAT_MIN;

        $variants = get_post_meta($post_id, 'custom_variants', true);

        foreach ($variants as $variant) {
            $width = floatval($variant['width']);
            $height = floatval($variant['height']);

            if ($width < $min_width) $min_width = $width;
            if ($width > $max_width) $max_width = $width;
            if ($height < $min_height) $min_height = $height;
            if ($height > $max_height) $max_height = $height;
        }

        wp_send_json([
            'min_width' => $min_width,
            'max_width' => $max_width,
            'min_height' => $min_height,
            'max_height' => $max_height
        ]);
    } else {
        wp_send_json(['error' => 'Produkt nie został znaleziony']);
    }

    wp_die();
}

add_action('wp_ajax_get_dimension_ranges', 'get_dimension_ranges');
add_action('wp_ajax_nopriv_get_dimension_ranges', 'get_dimension_ranges');






function enqueueCalculatorScript() {
    ?>
    <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
        var productTitleElement = document.querySelector('.product_title.entry-title');
        var productTitle = productTitleElement.innerText;

        // Fetch and display dimension ranges
        jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {
            'action': 'get_dimension_ranges',
            'product_title': productTitle
        }, function(response) {
            if (!response.error) {
                document.getElementById('min_szerokosc').textContent = response.min_width;
                document.getElementById('max_szerokosc').textContent = response.max_width;
                document.getElementById('min_wysokosc').textContent = response.min_height;
                document.getElementById('max_wysokosc').textContent = response.max_height;
            } else {
                console.error("Dimension range error:", response.error);
            }
        });

       
    var calculateButton = document.getElementById('calculate_price');
    if (calculateButton) {
        calculateButton.addEventListener('click', function() {
            var width = document.getElementById('product_width').value;
            var height = document.getElementById('product_height').value;
            var productTitleElement = document.querySelector('.product_title.entry-title');
            var productTitle = productTitleElement ? productTitleElement.innerText : '';

            jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', {
                'action': 'get_variants_for_calculation',
                'width': width,
                'height': height,
                'product_title': productTitle
            }, function(response) {
                var priceDisplay = document.getElementById('calculated_price');
                if (response.error) {
                    priceDisplay.innerHTML = 'Błąd: ' + response.error;
                } else {
                    var priceHtml = response.sale_price ?
                        '<s>' + response.regular_price + '</s> ' + response.sale_price :
                        response.regular_price;
                    priceDisplay.innerHTML = 'Cena: ' + priceHtml;

                    var addButton = document.getElementById('add_to_cart_button');
                    if (!addButton) {
                        addButton = document.createElement('button');
                        addButton.id = 'add_to_cart_button';
                        addButton.innerText = 'Dodaj do koszyka';
                        document.getElementById('product_calculator').appendChild(addButton);
                    }
                    addButton.setAttribute('data-variant-id', response.variant_id);
                    addButton.setAttribute('data-product-id', response.product_id);
                    addButton.setAttribute('data-width', width);
                    addButton.setAttribute('data-height', height);
                    addButton.setAttribute('data-price', priceHtml);
                }
            }, 'json');
        });
    }
});
jQuery(document).ready(function($) {
    $(document).on('click', '#add_to_cart_button', function(e) {
        e.preventDefault();
        var data = {
            'action': 'add_variant_to_cart',
            'product_id': $(this).data('product-id'),
            'variant_id': $(this).data('variant-id')
        };

        $.post(ajax_object.ajax_url, data, function(response) {
            if (response.success) {
                alert('Produkt dodany do koszyka');
                // Opcjonalnie: aktualizacja elementów UI, np. liczba przedmiotów w koszyku
            } else {
                alert('Błąd: ' + response.error);
            }
        });
    });
});


  
    </script>
    <?php
}
add_action('wp_enqueue_scripts', 'enqueueCalculatorScript');



function getVariantsForCalculation() {
    $product_title = isset($_POST['product_title']) ? sanitize_text_field($_POST['product_title']) : '';
    $client_width = isset($_POST['width']) ? floatval(sanitize_text_field($_POST['width'])) : 0;
    $client_height = isset($_POST['height']) ? floatval(sanitize_text_field($_POST['height'])) : 0;

    $query = new WP_Query([
        'post_type' => 'product',
        'title' => $product_title
    ]);

    if ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        $variants = get_post_meta($post_id, 'custom_variants', true);

        $nearestVariant = null;
        $smallestDistance = PHP_FLOAT_MAX;

        foreach ($variants as $variant) {
            $distance = sqrt(pow($variant['width'] - $client_width, 2) + pow($variant['height'] - $client_height, 2));
            if ($distance < $smallestDistance) {
                $smallestDistance = $distance;
                $nearestVariant = $variant;
            }
        }

        if ($nearestVariant) {
            echo json_encode([
                'variant_id' => $nearestVariant['id'],
                'regular_price' => $nearestVariant['regular_price'],
                'sale_price' => $nearestVariant['sale_price'],
                'dimensions' => $nearestVariant['width'] . 'x' . $nearestVariant['height'],
                'product_id' => $post_id
            ]);
        } else {
            echo json_encode(['error' => 'No matching variant found']);
        }
    } else {
        echo json_encode(['error' => 'Product not found']);
    }

    wp_die();
}



add_action('wp_ajax_get_variants_for_calculation', 'getVariantsForCalculation');
add_action('wp_ajax_nopriv_get_variants_for_calculation', 'getVariantsForCalculation');





// Dodanie funkcji do akcji AJAX dla zalogowanych i niezalogowanych użytkowników
function add_variant_to_cart() {
    if (!isset($_POST['product_id'], $_POST['variant_id'])) {
        wp_send_json_error(['error' => 'Brakujące dane produktu']);
        wp_die();
    }

    $product_id = intval($_POST['product_id']);
    $variant_id = sanitize_text_field($_POST['variant_id']);
    
    // Pobierz metadane wariantów
    $variants = get_post_meta($product_id, 'custom_variants', true);
    $selected_variant = array_filter($variants, function($v) use ($variant_id) {
        return $v['id'] === $variant_id;
    });

    if(empty($selected_variant)) {
        wp_send_json_error(['error' => 'Wariant nie istnieje']);
        wp_die();
    }

    $selected_variant = array_values($selected_variant)[0];

    $cart_item_data = array(
        'custom_dimensions' => $selected_variant['width'] . 'x' . $selected_variant['height'],
        'custom_price' => $selected_variant['sale_price'] ? $selected_variant['sale_price'] : $selected_variant['regular_price'],
        'stock_status' => $selected_variant['stock_status']
    );

    $cart_item_key = WC()->cart->add_to_cart($product_id, 1, 0, array(), $cart_item_data);

    if (!$cart_item_key) {
        wp_send_json_error(['error' => 'Nie udało się dodać produktu do koszyka']);
        wp_die();
    }

    wp_send_json_success(['success' => 'Produkt dodany do koszyka']);
    wp_die();
}


add_action('wp_ajax_add_variant_to_cart', 'add_variant_to_cart');
add_action('wp_ajax_nopriv_add_variant_to_cart', 'add_variant_to_cart');


function set_custom_price_for_cart_items($cart) {
    if (is_admin() && !defined('DOING_AJAX')) {
        return;
    }

    foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
        if (isset($cart_item['custom_price'])) {
            $cart_item['data']->set_price($cart_item['custom_price']);
        }
    }
}
add_action('woocommerce_before_calculate_totals', 'set_custom_price_for_cart_items', 10, 1);

Error (index):3156 crbug/1173575, non-JS module files deprecated. in my extension

manifest.json:

{
    "name": "setence break down py",
    "version": "0.1.0",
    "description": "Destrinchar sentenças gramaticalmente",
    "permissions": ["tabs", "activeTab", "contextMenus", "webRequest", "storage"],
    "host_permissions": ["<all_urls>"],
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
        "matches": ["<all_urls>"],
        "js": ["contentScript.js"]
        }
    ],

    "action": {
        "default_popup": "breakdown.html",
        "default_title": "sentence breakdown"
    },
    "manifest_version": 3
}

background.js:

/*const { OpenAI } = require('openai');*/

chrome.runtime.onInstalled.addListener(function() {
  chrome.contextMenus.create({
    id: "acionarpy",
    title: "acionarpy",
    contexts: ["selection"]
  });
});

var selecao

chrome.contextMenus.onClicked.addListener(function(info, tab) {

  selecao = info.selectionText
  if (info.menuItemId === "acionarpy") {
    chrome.windows.create({
        type: "popup",
        url: "breakdown.html",
        width: 300,
        height: 200
    });
  }
});

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
  if (message.action === "janelaCriada") {
      console.log("menssagem")
      console.log(selecao)
      sendResponse({
        resposta: selecao
      })
  }
});

contentScript.js:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
    if (message.action === "janelaCriada") {
        console.log( window.getSelection().toString())
        sendResponse({
          resposta: "cs"
        })
    }
  });

breakdown.html:

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <title>breakdown</title>
</head>
<body>
    <!--<main class="container-fluid py-5 text-center">
        {% block main %}{% endblock %}
    </main>-->
    <div>
        <h2>Texto selecionado: </h2>
        <p id="selectedText">-</p>
    </div>

    <form name="call" id="call" action="/call" method="post">
        <input type="text" value="">
    </form>

    <div>
        <p id="tg">+</p>
    </div>

    <script src="breakdown.js"></script>
</body>
</html>

breakdown.js:




var texto

window.onload = function() {
  console.log("breakdown");

  chrome.runtime.sendMessage({action: "janelaCriada"}, async function(response){
    console.log("menssagem no breakdown:")
    console.log(response.resposta)
    texto = response.resposta
    console.log("texto:", texto)
    document.getElementById("selectedText").textContent = response.resposta
    document.querySelector('input[type="text"]').value = response.resposta
    document.call.submit();
  });
};

teste.py:

from flask import Flask, flash, redirect, render_template, request, session, g
from flask_session import Session

import os
import google.generativeai as genai

app = Flask(__name__)

@app.route("/call", methods=["GET", "POST"])
def api_call():

    if request.method == 'POST':
        call_prompt = request.form.get("call")
        print(call_prompt)
        return None
    

if __name__ == '__main__':
    app.run()

this is what the popup console looks like:

menssagem
background.js:29 trouble
(index):3156 crbug/1173575, non-JS module files deprecated.
(anonymous) @ (index):3156

why is this error happening?

I wanted to send the form value to the flask app (i’m planning to do something else with this value in there), and print it, so i could test the value update

how to write javascript code that automates searches on bing?

i’m a regular user of microsoft rewards, and one major way to get points is to search around thirty unique queries on bing. each search has to have around seven seconds of time in between for it to count towards point progress. normally i have a loop timer going and just search random letters. like d (seven seconds) s (seven seconds) d (seven seconds) s and so on until the search bar looks like dsdsdsdsds dsdsdsdsds dsdsdsdsds lol!! i want to make this process easier thru a tampermonkey javascript script but i only have limited knowledge in python. can anyone give me a nudge in the right direction of what functions or lines to look into? thanks for any help! i’m not sure where to start.

disable a button of the last of a table which was created from a loop in vue.js 2

I have two components which set the button and where the button component is called there is a v-for to loop through other items. Now i want the button inside the last or if there is only one generated to be disabled.

Here is my code

<template>
  <div class="clickable-text" @click="() => !disabled && onClick()">
    <div :class="className">{{ text }}</div>
    <IconSpinner v-if="loading" class="ml-1" />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
@Component({})
export default class ClickableText extends Vue {
  @Prop({ default: true }) text: string;
  @Prop({ default: 'default' }) disabled: boolean;
  @Prop() classes: string;
  @Prop({ default: true }) clickable: boolean;
  @Prop({ default: () => {} }) onClick: () => void;
  @Prop({}) loading: boolean;

  get className() {
    return {
      disabled: this.disabled,
      [this.classes]: this.classes,
      clickable: this.clickable && !this.disabled,
    };
  }
}
</script>

The above component is used inside

<component :is="item[header.value].component" v-bind="item[header.value].props" />

, the {{text}} prop is within v-bind=”item[header.value].props”

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header.value">
            <div @click="headerClicked(header)">
              {{ header.text }}
            </div>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, n) in items" :key="n" data-qa="row" :id="item.id ? item.id.value : n">
          <td v-for="header in headers" :key="header.value" :data-qa="header.value">
            <div :class="itemClass(item, header)" @click="itemClicked(item, header)">
              <div v-if="item[header.value] && item[header.value].value">{{ item[header.value].value }}</div>
              <div v-else>
                <component :is="item[header.value].component" v-bind="item[header.value].props" />
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator';
import { TableHeader, TableItem, TablePagination, AppTableItemClick } from './interfaces';

@Component
export default class AppTable extends Vue {
  @Prop() headers: TableHeader[];
  @Prop() items: TableItem[];
  @Prop() pagination?: TablePagination;

  itemClass(item: TableItem, header: TableHeader) {
    const isClickable = item[header.value]?.clickable;
    return { link: isClickable, clickable: isClickable };
  }

  headerClicked(header: TableHeader) {
    if (header.sortable) {
      this.$emit('headerClicked', header);
    }
  }

  itemClicked(item: TableItem, header: TableHeader): AppTableItemClick | undefined {
    const headerName = header.value;
    if (item[headerName]?.clickable) {
      const returnValue = { item, id: headerName };
      this.$emit('itemClicked', returnValue);
      item[headerName]?.onClick?.();
      return returnValue;
    }
  }
}
</script>

The result of the loop is like this and I want to disable Hide contact button if it is the only item or last item.

enter image description here

How to make “pong” animation

I’m a little lost and new to this.

So the code is with the help of online resources. How can I basically combine all three of these elements to appear and move at the same time? I want it to look like the game pong.

I understand why the canvas needs to be cleared for animations but why are they still “on top” of each other? How can I get all 3 into view?

const canvas = document.getElementById("pong")
const ctx = canvas.getContext("2d");

//ball//
const ball = {
    x: 100,
    y: 100,
    vx: 5,
    vy: 2,
    radius: 8,
    color: "red",
    draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.fillStyle = this.color;
        ctx.fill();
    },
};

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ball.draw();
    ball.x += ball.vx;
    ball.y += ball.vy;

    if (
        ball.y + ball.vy > canvas.height - ball.radius ||
        ball.y + ball.vy < ball.radius
    ) {
        ball.vy = -ball.vy;
     }
    if (
        ball.x + ball.vx > canvas.width - ball.radius ||
        ball.x + ball.vx < ball.radius
    ) {
        ball.vx = -ball.vx;
    }

    raf = window.requestAnimationFrame(draw);
}

canvas.addEventListener("mouseover", (e) => {
    raf = window.requestAnimationFrame(draw);
});

canvas.addEventListener("mouseout", (e) => {
    window.cancelAnimationFrame(raf);
});


ball.draw();


// pong paddles //

ctx.strokeStyle = "purple";
var posY = 0;
var lineLength = 80;
var lineWidth = 10;
var speed = 2;

function drawLine() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(10, posY);
    ctx.lineTo(10, posY + lineLength);
    ctx.stroke();
}

function moveLine() {
    posY += speed;

    if (posY < 0 || posY > canvas.height) {
        speed = speed * -1;
    }
}

function loop() {
    // clear old frame;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    moveLine();
    drawLine();
    requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

//Paddle 2//

ctx.strokeStyle = "purple";
var posY = 0;
var lineLength = 80;
var lineWidth = 10;
var speed = 2;

function drawLine() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(200, posY);
    ctx.lineTo(200, posY + lineLength);
    ctx.stroke();
}

function moveLine() {
    posY += speed;

    if (posY < 0 || posY > canvas.height) {
        speed = speed * -1;
    }
}

function loop() {
    // clear old frame;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    moveLine();
    drawLine();
    requestAnimationFrame(loop);
}
requestAnimationFrame(loop);

How to add a new line in textContent in javascript

function callBack(data1, predicted_label){
    const resultParagraph = document.getElementById("resultParagraph"); 
    resultParagraph.textContent = `Sentiment: ${predicted_label}`;
    const historyList = document.getElementById("historyList");
    const listItem = document.createElement('li');
    listItem.textContent = `Text: ${data1} Sentiment: ${predicted_label}`;
    historyList.prepend(listItem);  }

In this code i want to add a new line between Text: ${data1} Sentiment: ${predicted_label}.

I’ve tried adding n, tried adding a <br> tag but nothing seems to work

Javascript to CSS fails

I am making a weather like app. the JS file i use, has a script that makes the background image change to whatever the condition is, Now the issue is; that the image URL is wrong. I’ve tried anything possible, it stays on url(“../img/((condition name)).jpg”) (the (( and )) were made by me for a example) instead of url(“../website/assets/img/((condition name)).jpg”)

The code:

JS:

const updateWeatherFrame = (city) => {
  if (!city) {
    console.error("No city provided for weather update.");
    return;
  }

  const weatherApiUrl = `https://api.weatherapi.com/v1/current.json?        key=${process.env.WEATHER_API_KEY}&q=${city}&aqi=yes`;

  fetch(weatherApiUrl)
    .then((response) => {
      if (!response.ok) {
        throw new Error("Failed to fetch weather data");
      }
      return response.json();
    })
    .then((data) => {
      const currentCondition = data.current.condition.text;
      let backgroundImage = "url('./assets/img/default.jpg')";

      for (const entry of conditionToImageMapping) {
        if (entry.conditions.includes(currentCondition)) {
          backgroundImage = `url('./assets/img/${entry.image}')`;
          break;
        }
      }
      const weatherFrame = document.getElementById("weatherframe");
      if (weatherFrame) {
        weatherFrame.style.backgroundImage = backgroundImage;
      }
    })
    .catch((error) => {
      console.error("Error fetching weather data:", error);
    });
};

document.addEventListener("DOMContentLoaded", () => {
  updateWeatherFrame("New York"); // Example city for initial update
  setInterval(() => updateWeatherFrame("New York"), 300000); // Update every 5 minutes
});

CSS:

.weatherfr {
  width: 100%;
  height: 500px;
  background-color: lightblue;
  background-size: cover;
  /* Ensures the image covers the entire DIV */
  background-position: center;
  /* Centers the image */
  background-repeat: no-repeat;
  /* Prevents image repetition */
  transition: background 0.5s ease;
  /* Smooth transition */
}

HTML:

<div id="weatherframe" class="weatherfr">

</div>
<!-- Link to the JavaScript file -->
<script src="../website/assets/js/weather.js"></script>

I tried to set the background image of the div to the image, yet only the background image displays. I expected it to have the path i mentioned above.

(Editor.js) Editor is rendering twice for one holder id. (react js)

I’m creating a web app that requires text-editor. I’m relatiely new to react and coding. And I’m using Editor.js. I need multiple editors on one page. So, here’s what I did:

const PRIORTY_TYPES = [
    { id: 0, name: "p1", type: 1 },
    { id: 1, name: "p2", type: 2 },
    { id: 2, name: "p3", type: 3 },
    { id: 3, name: "other", type: 4 },
];

I created an array of priority types and I’m mapping it to create multiple editors.

To change the id of the container div for editor i’m using somthing like this.

const PriorityBlock = ({ priorityType }) => {
    const editorRef = useRef(null);

    const initEditor = () => {
        const editor = new EditorJS({
            holder: `${EDITOR_HOLDER_ID}-${priorityType}`,
            onReady: () => {
                editorRef.current = editor;
                new Undo({ editor });
            },
            autofocus: false,
            minHeight: 16,
            data: DEFAULT_INITIAL_DATA,
            onChange: async () => {
                let content = await editor.saver.save();
                console.log(content);
            },
            tools: {
                checklist: {
                    class: Checklist,
                    inlineToolbar: true,
                    tunes: ["anyTuneName"],
                },
                list: {
                    class: List,
                    inlineToolbar: true,
                    config: {
                        defaultStyle: "unordered",
                    },
                    tunes: ["anyTuneName"],
                },
                anyTuneName: {
                    class: AlignmentTuneTool,
                    config: {
                        default: "left",
                    },
                },
            },
        });
    };

    useEffect(() => {
        if (!editorRef.current) {
            initEditor();
        }

        return () => {
            editorRef.current?.destroy();
            editorRef.current = null;
        };
    }, []);

    return (
        <div
            id={`${EDITOR_HOLDER_ID}-${priorityType}`}
            className={`${styles.editorjs} primaryFont`}
        />
    );
};

When I run the code for the first time. It runs smoothly. But after a refresh there are 2 instances of same editors. i.e one holder id div has 2 editors.

Only solution I found is removing the strict mode in react. But I might need that for other purposes since it’s there for a reason. Can anybody tell me what’s causing this problem?

Why does svelteKit/Node only load js and other assets on the homepage?

It seems the build of my sveltekit site on a nodejs server will load all assets when on the homepage, and carries them to pages, but loading directly onto a page will not load the proper resources.

Properly Loaded Page
Once on the homepage, all assets are loaded, and the site acts properly. The assets stay loaded navigating from page to page, but refeshing or just directly following a url breaks this.

Site with no assets
If the page is refreshed while not on the homepage, none of the assets seen in inspect have loaded, and the onMount JS function did not run and load the header properly.

I have made sure all node modules are up to date, and I am running Node 20.12. However I have little experience with svelte sveltekit and node. Any thoughts on what I need to do to fix this?