Joi validator validateAsync remove warnings

I have been using Joi library for validation user inputs like this.

const Joi = require('joi');

const schema = Joi.object({
    username: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required()
});

const validationResult = await schema.validateAsync({ username: 'a' }, { abortEarly: false, warnings: true });

This works fine, the problem is later in code I would want to use this validation again.
But the warning messages are still in the local context.

And if I input he { username: ‘ba’} the error message will still display that min length of “a” needs to be 3.

Do you know how can I use the schema object again, and strip the local warnings context.

Trying to check for form errors

I’m using the code below. The script thinks the checkbox is checked. It is not checked.

if (!document.f1.SK_1.checked && document.f1.SK_Number1.value == "") {
alert("Please enter your profile link");
document.f1.SK_Number1.focus();
return false;
}

if (!document.f1.SK_2.checked && document.f1.SK_Number2.value == "") {
alert("Please enter your profile link");
document.f1.SK_Number2.focus();
return false;
}

<input class="selectRadioButtons" type="checkbox" name="SK_1"  value="$provlist[0]" > <BR>
<input class="selectClass" type="text" name="SK_Number1" value="" placeholder="$provlist[0] Profile Link"> 

FFMPEGWASM won’t load version 12 reference error

I’ve written a simple script to load FFMPEGWASM but it gives an error:

Error loading FFmpeg: ReferenceError: Can’t find variable: FFmpeg

Full code is here

<h1>FFmpeg Loading Example</h1>
<p id="message"></p>
<script src="https://cdn.jsdelivr.net/npm/@ffmpeg/[email protected]/dist/umd/ffmpeg.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", async () => {
        const message = document.getElementById('message');
        try {
            const ffmpeg = new FFmpeg();
            message.innerText = 'Loading FFmpeg...';
            await ffmpeg.load();
            message.innerText = 'FFmpeg loaded successfully!';
        } catch (error) {
            console.error('Error loading FFmpeg:', error);
            message.innerText = 'Error loading FFmpeg.';
        }
    });
</script>

Why does HighCharts call go to an external server when I’m using offline exporting

I decided to use offlineclient side exporting and based on the information shown in Highcharts Client Side exporting it shows that all I need to do is add a link to offline-exporting.js. I have done this and I get a CORS error saying my attempt to access https://export-svg.highcharts.com is blocked by CORS restriction. Why is the offline exporting even attempting to go to an outside link? I thought the idea of offline exporting/client side exporting was that the chart information was not to be passed to an external server and instead served up via my web browser.

For reference I’m using Chrome Version 131.0.6778.205 and HighCharts version 12.1.1. I’m running the application on my machine (localhost). I am not using any custom code to call the chart

So I’m wondering why is an offline/client side exporting leaving and trying to access an external server? How do I go about fixing this as all I see according to the documentation is to just add the offline-exporting.js link after the exporting.js link?

Thanks in advance,
Bob

Serving .js and .css from Vite + Svelte to a static website

I have a pre-existing website using a popular website builder.

I want to be able to inject interactive svelte components on certain blog pages to help demonstrate concepts.

I got a rough prototype working with Vite + Svelte, but I’m wondering how I can improve upon it, specifically with Hot Module Reloading so I don’t have to refresh the page every time to see the updated Svelte component.

From a barebones Vite Svelte template, I made the following modifications to vite.config.ts:

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

// https://vite.dev/config/
export default defineConfig({
  plugins: [svelte()],
  build: {
    manifest: true,
    rollupOptions: {
      output: {
        entryFileNames: `assets/[name].js`,
        chunkFileNames: `assets/[name].js`,
        assetFileNames: `assets/[name].[ext]`
      }
    }
  }
})

When I run my build command, the filenames are no longer hashed so I can access them without updating URLs. If I enable my local web server I now get more permanent URLs to the JS and CSS files.

In my website builder, I can now develop and use the svelte component like so:

<script type="module" crossorigin src="http://127.0.0.1:5500/dist/assets/index.js"></script>
<link rel="stylesheet" crossorigin href="http://127.0.0.1:5500/dist/assets/index.css" />

(Eventually this code will be served from CDN but for now I want to be able to develop from my local machine)

In my website builder, I just give a div the proper id (I’m using counter) and update the main.ts file accordingly:

import { mount } from 'svelte'
import App from './App.svelte'

const app = mount(App, {
  target: document.getElementById('counter')!,
})

export default app

Basically, I’m trying to build out a good workflow to inject small Svelte apps into my existing website. Vite seems to default to bundling everything inside index.html, but I’m looking to override that behavior, and inject the .js and .css into the html files built by my website builder. I think the adding HMR would really take this workflow to the next level, but I can’t figure out how to do that with my current setup.

jsDoc to define constructor function properties that are assigned implicitly (not set with `this`)

Using jsDoc in VS Code, How could we define the properties of a constructor function that its properties are not set directly through this.property = value syntax, but implicitly via Object.assign() code as in following sample:

/** 
 * @constructor
 * @property {string} title - the @property here has no effect to define such properties to IDE 
 */
function BookFn(title, description, year, author, lang, genre, pages, isbn, copies) {
  
  //instead of writing multiple this.x = y code,
  //we set our properties indirectly via 'Object.assign()' as follow:
  Object.assign(this, {title, description, year, author, lang, genre, pages, isbn, copies}); 
  
}

BookFn.prototype = {
  titleAuthor() { return this.title + ' by ' + this.author}, //VSCode IDE doesn't know such properties!
};

let book1 = new BookFn('book1', 'description1', 2020, 'author1', 'English', 'genre1', 600, 'isbn1', 5000);
let t = book1.title; //VSCode IDE doesn't know such property!

I have tried the @property to define explicitly our properties but it doesn’t have any effect.

How to remove a box using Javascript? [closed]

In this library app I’ve added trash bins on each card at the bottom right of each box. I would like to add the functionality to actually delete each card (grid item) by clicking on its corresponding trash bin.

I’m new to javascript and I don’t know how to do this yet

It says it needs more details but I don’t know what to add besides this so I’ll just leave this note here and see if it accepts it this time.

const myLibrary = [
  { title: 'A storm of Swords', author: 'George R. R. Martin', numOfPages: '1008 pages', hasRead: true ? 'Read.' : "Hasn't been read yet" },
  { title: 'A Game of Thrones', author: 'George R. R. Martin', numOfPages: '720 pages', hasRead: false ? 'Read.' : "Hasn't been read yet" },
  { title: "The Hobbit", author: "J.R.R. Tolkien", numOfPages: "295 pages", hasRead: true ? "Read." : "Hasn't been read yet." }
];

function Book(title, author, numOfPages, hasRead) {
  this.title = title;
  this.author = author;
  this.numOfPages = numOfPages;
  this.hasRead = hasRead;
  this.info = function() {
    return `${title} by ${author}, ${numOfPages}, ${hasRead}`;
  }
}

const deleteCard = document.querySelector('.grid-item svg');
console.log(myLibrary[0]);

function addBook() {
  const fTitle = document.getElementById("bookTitle").value;
  const fAuthor = document.getElementById("author").value;
  const fNumOfPages = document.getElementById("numOfPages").value;
  const fHasRead = document.getElementById("hasRead").checked ? "Read." : "Hasn't been read yet.";

  if (fTitle && fAuthor && fNumOfPages) {
    const newBook = new Book(fTitle, fAuthor, fNumOfPages, fHasRead);
    
    addBookToLibrary(newBook);
  
    const gridItem = document.createElement("div");
    gridItem.className = "grid-item";

    // Add content to the grid item
    gridItem.innerHTML = `
      <svg xmlns="http://www.w3.org/2000/svg" width="4px" height="54px" viewBox="0 0 384 512"><!--! Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><style>svg{fill:#ffffff}</style><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/></svg>
      <h3>${newBook.title}</h3>
      <p>${newBook.author}</p>
      <p>${newBook.numOfPages}</p>
      <p>${newBook.hasRead}</p>
    `;
    gridContainer.appendChild(gridItem);
  }
}

function addBookToLibrary(book) {
  myLibrary.push(book);
}

/////////////////////////

const modal = document.querySelector('.modal');
const openModal = document.querySelector('.open-button');
const closeModal = document.querySelector('.close-btn');

openModal.addEventListener('click', () => {
  modal.showModal();
});

closeModal.addEventListener('click', () => {
  modal.close();
})

/////////////////////////

const gridContainer = document.getElementById("gridContainer");

function updateGrid() {
  myLibrary.forEach(item => {
  // Create a div for each grid item
  const gridItem = document.createElement("div");
  gridItem.className = "grid-item";

  // Add content to the grid item
  gridItem.innerHTML = `
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M135.2 17.7L128 32 32 32C14.3 32 0 46.3 0 64S14.3 96 32 96l384 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-96 0-7.2-14.3C307.4 6.8 296.3 0 284.2 0L163.8 0c-12.1 0-23.2 6.8-28.6 17.7zM416 128L32 128 53.2 467c1.6 25.3 22.6 45 47.9 45l245.8 0c25.3 0 46.3-19.7 47.9-45L416 128z"/></svg>
    <h3>${item.title}</h3>
    <p>${item.author}</p>
    <p>${item.numOfPages}</p>
    <p>${item.hasRead}</p>
  `;

  // Append the grid item to the container
  gridContainer.appendChild(gridItem);
})};

updateGrid();
* {
  box-sizing: border-box;
}

dialog::backdrop {
  background: rgb(0 0 0 / .4);
}

.modal {
  padding: 1.5em;
  max-width: 50ch;
}

dialog {
  border: 2px solid black;
  border-radius: 12px;
}

.close-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    background: none;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
}

body {
  background-color: rgb(215, 137, 28);
}

dialog label {
  font-size: 18px;
  display: block;
  padding: 8px 0 8px;
}

dialog input[type=checkbox] {
  display: block;
  margin: 0 0 16px;
}

dialog input[type=text],
dialog input[type=number] {
  width: 100%;
}

dialog h2 {
  margin: 0 0 10px;
}

dialog text {
  width: 100%;
}

.close-button {
  margin-bottom: 10px;
}

h2 { 
  padding-right: 22px;
}

/* input:invalid {
  outline: 2px solid red;
}

input:valid {
  border: 2px solid black;
} */

/* -------------------- */
/* --------GRID-------- */
/* -------------------- */

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  padding: 16px;
}
.grid-item {
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  background-color: #f9f9f9;
  position: relative;
}
.grid-item h3 {
  margin: 0 0 8px;
}
.grid-item p {
  margin: 0;
  color: #666;
}
.fa-trash {
  position: absolute;
  z-index: 101;
}
.grid-container .grid-item {
  position: relative;
}

.grid-item svg {
  height: 20px;
  width: 20px;
  position: absolute;
  right: 15px;
  bottom: 15px;
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
  <script src="https://kit.fontawesome.com/e8fb2c6b62.js" crossorigin="anonymous"></script>
</head>
<body>
  <h2>An interesting title</h2>
    <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Amet maiores placeat dolorum corporis nihil sapiente cupiditate animi rem ab tenetur facilis ad hic corrupti eligendi, nulla labore, impedit eveniet repudiandae!</p>
    
  <button class="button open-button">open modal</button>
  
  <dialog class="modal" id="modal">
    <h2>Enter details</h2>

    <form class="form" method="dialog">
      
      <label>Book Title </label>
      <input type="text" id="bookTitle" required />

      <label>Author </label>
      <input id="author" type="text" id="author" required />

      <label>Number of pages </label>
      <input type="number" id="numOfPages" required />

      <label>Click if you've finished reading it</label>
      <input type="checkbox" id="hasRead" />

      <input id="addBookBtn" type="submit" onclick="addBook()" />
    </form>
    <button class="close-btn" id="closeDialog">&times;</button>
  </dialog>

  <div class="grid-container" id="gridContainer">
    
  </div>

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

How to handle JavaScript reinitialization for dynamically loaded AJAX content with WordPress script dependencies?

I am dynamically loading content via AJAX and appending it to the frontend. While the content loads successfully, the issue arises with initializing JavaScript functionality for the newly loaded elements, especially in a WordPress environment where scripts have dependencies.

What I have tried:

Extracting and registering scripts from the AJAX response:
I attempted to extract all tags from the AJAX response and dynamically load them one by one using the following approach:

$.ajax({
    url: 'your-endpoint',
    success: function(data) {
        const content = $(data);
        $('#content-container').html(content);

        // Extract scripts and reinitialize
        content.find('script').each(function() {
            const script = document.createElement('script');
            script.src = $(this).attr('src') || '';
            script.text = $(this).html();
            document.head.appendChild(script);
        });
    }
});

This approach works in some cases, but in WordPress, many scripts rely on dependencies registered with wp_enqueue_script. Without those dependencies being properly enqueued, I encounter errors like:

ReferenceError: wp is not defined

My Question:
How can I properly handle JavaScript initialization for dynamically loaded AJAX content in WordPress, ensuring all dependencies are resolved?

Is there a way to automatically re-register or reinitialize WordPress scripts (and their dependencies) for dynamically loaded content without manually enqueueing them beforehand?

I’m looking for a scalable solution that aligns with WordPress best practices.

How can I properly handle JavaScript initialization for dynamically loaded AJAX content in WordPress, ensuring all dependencies are resolved?

Is there a way to automatically re-register or reinitialize WordPress scripts (and their dependencies) for dynamically loaded content without manually enqueueing them beforehand?

I’m looking for a scalable solution that aligns with WordPress best practices.

How to make OneTrust and Google Maps to work nicely

The company I work for uses OneTrust to handle GDPR. I have the task to make a google map show up. I have had issues making the https://maps.googleapis.com/maps/api script tag to work as I wanted to use a library. Anyway I got it working by adding the attribute data-ot-ignore to the script tag. But now the maps thing is not calling my back end to get the layers I need to put on top of the map. I have an API that I call and it works fine in a local, contrived sample but once it’s on the full blown test environment it just won’t call my API to get the layers

The way google maps retrieves the layers is by calling the function in the ImageMapTyle object we have to define:

  new google.maps.ImageMapType({
    getTileUrl(coord, zoom): string {
      return `${coverage_rest_root}/tiles/service/gmaps?layers=${layerProps[overlayRev].apiName}&zoom=${zoom}&x=${coord.x}&y=${coord.y}&format=image/png`;
    },
    tileSize: new google.maps.Size(TILE_SIZE, TILE_SIZE),
    opacity: layerProps[overlayRev].opacity,
    name: overlayRev,
  });

which makes me not be able to add neither a class nor an attribute, which are the two ways to tell OneTrust to ignore the script

Is there a way to call reusable rules in javascript block as the following: testRigor.execute(“my reusable rule with ‘param1′”)?

Trying to achieve the following but it ends up just blocking the server and never finishing the execution even when cancelling the test run:

    execute JavaScript text starting from next line and ending with [END]
        var tenantName = "Ford CSP";
        testRigor.execute('map tenant name "' + tenantName + '" to vinDecoder domain');
    [END]

To execute a resuable rule in a javaScript block

How to flatten a tree of table columns into a flat list of table columns with headers

I have a nested tree of table columns. Here are the typescript types.

export interface TableLeafColumn {
  label: string;
  key?: string;
}

export interface TableContainerColumn {
  label: string;
  columns: TableColumn[];
}

// Union type to represent either a leaf or container column
export type TableColumn = TableLeafColumn<T> | TableContainerColumn;

Here’s an example of such a type:

const columns: TableColumn[] = [
  {
    label: "Name",
    key: "name",
  },
  {
    label: "Details",
    columns: [
      {
        label: "Age",
        key: "age",
      },
      {
        label: "Address",
        columns: [
          { label: "City", key: "city" },
          { label: "Country", key: "country" },
        ],
      },
    ],
  },
];

I would like a function called flattenColumns that will return TableColumn[][]. For example, the input above would return:

const result = [
  [
    { label: "" }, // placeholder for Name
    { label: "Details", colSpan: 3 }
  ],
  [
    { label: "" }, // placeholder for Name
    { label: "" }, // placeholder for Age
    { label: "Address", colSpan: 2  }
  ],
  [
    { label: "Name", key: "name" },
    { label: "Age", key: "age" },
    { label: "City", key: "city" },
    { label: "Country", key: "country" },
  ]
]

I have tried to write the function, but nothing worked. The tricky party is adding the placeholders, so that every leaf column appears at the bottom.

Not sure if the result I gave above is the best representation for this, but I want to render such table headers inside an HTML table, and I figured that format would be the easiest to utilise.

JS fetch headers are not included before request (Flask)

I’m using JS to get the screen width of the page, posting it, and then calling it from within my Flask app HTML template to determine functionality of a graph (either interactive Plotly or an image). I am correctly getting the width, but I have errors either “415 Unsupported Media Type Did not attempt to load JSON data because the request Content-Type was not ‘application/json'” or “Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON”

If I don’t call the data = request.get_json() line in app.py, I get the second error; it seems like the fetch body is not executing properly and it’s just getting the whole page. If I call this line, I get the Unsupported Media Type error, the headers don’t log, and the print statement regarding the DOM loading doesn’t load either.

I’m very new to JS and just want to get the screen width and pass it back to the Flask app. It seems like even though I have document.addEventListener('DOMContentLoaded', () that if I call request.get_json() the code executes before the headers are loaded.

Here are my code snippets:

JS

    document.addEventListener('DOMContentLoaded', () => {
        console.log('dom loaded')
        const playlistId = '{{ playlist.playlist_id }}';
        const width = window.innerWidth;
        const headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        };
        console.log('Headers being sent:', headers);
        fetch(`/playlist/${playlistId}`, {
            method: 'POST',
            headers: headers,
            body: JSON.stringify({ width: width })
        })
        .then(response => {
            console.log('Raw response:', response);
            return response.json();
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });

playlist.html (jinja)

    {% if viewport >= 768 %}
        {% for graph in graphs %}
        <div class="features-graph">
            {{ graph[0]|safe }}
        </div>
        {% endfor %}
    {% else %}
        {% for graph in graphs %}
        <div class="features-graph">
            <img src="data:image/jpg;base64,{{ graph[1] }}">
        </div>
        {% endfor %}
    {% endif %}

app.py

@app.route('/playlist/<string:playlist_id>', methods=['POST', 'GET'])
def playlist_details(playlist_id):
    playlist = Playlist.query.filter_by(playlist_id=playlist_id).first_or_404()
    playlist_tracks = Track.query.filter_by(playlist_id=playlist_id).all()
    sorted_playlists = model_playlists(playlist_id)
    graphs = make_graphs(playlist_id)
    data = request.get_json()
    viewport_width = data['width']
    return render_template('playlist.html', playlist=playlist, playlist_tracks=playlist_tracks, model_playlists=sorted_playlists, graphs = graphs, viewport=viewport_width)

I’m also open to another way to do this without JS or without the POST request.

Can I have controller for custom html element (to get context buttons update and delete)?

not sure if I am asking correctly. But I understood that controller is probably what I need. I want to have the functionality of custom plugin number 4 called Dialog – http://suneditor.com/sample/html/customPlugins.html#dialog But I do not want to insert a link but custom element named for example customElement.

I can modify the code provided for the sample plugin to custom HTML element is inserted but then I will loose the context dialog to update, unlink, or remove the element.

I my case I want only the update and remove icons.

enter image description here

Is that possible in Suneditor?

You test with https://jsfiddle.net/radek/qjoevast/12/ the very first line defines what HTML element is going to be inserted.

for var customElement = 'a' I get the context buttons
for var customElement = 'customElement' the correct element is inserted but not context buttons

We need to move the subchart to the top using billboard.js

Can anyone find the solution of the problem that I want to move the chart to top then mainchart in browser.Please let us know how to resolve this

I want to move the subchart at the top then mainchart should display in browser.

var chart = bb.generate({
  data: {
    columns: [
    ["sample", 30, 200, 100, 400, 150, 250]
    ],
    type: "line", // for ESM specify as: line()
  },
  subchart: {
    show: true, // for ESM specify as: subchart()
    showHandle: true
  },
  bindto: "#subChart"
});

Difficulty Connecting to Supabase S3-Compatible Storage

I am trying to connect to Supabase’s S3-compatible storage but am encountering some difficulties. The Supabase endpoint I am working with is structured as follows:

https://xxxxxxxxxxxx.supabase.co/storage/v1/s3

Could you provide guidance or examples on how to establish a connection to this endpoint? Any help or documentation links would be greatly appreciated.

InvalidEndpointError: Invalid endPoint : xxxxxxxxxxxxxx.supabase.co/storage/v1/s3
    at new TypedClient (file:///home/node/.cache/deno/npm/registry.npmjs.org/minio/8.0.2/dist/esm/internal/client.mjs:58:13)
    at new Client (file:///home/node/.cache/deno/npm/registry.npmjs.org/minio/8.0.2/dist/esm/minio.mjs:32:8)

}
    this.client = new Client({
      endPoint: S3_ENDPOINT,
      port: S3_PORT,
      useSSL: S3_SSL,
      region: S3_REGION,
      accessKey: S3_ACCESS_KEY,
      secretKey: S3_SECRET_KEY,
      pathStyle: true,
    });