Is there a way to have a dark background and “reveal” color using my mouse?

I’m trying to code my own website for the first time and I’m running into some trouble. I’m following this tutorial in order to have a spotlight follow my mouse. Here’s the code. But I’d like to have a rainbow gradient across my entire homepage and have my spotlight show color as it’s moving across the page while keeping the other parts of the screen dark, more similar to how the original website, that the youtube tutorial is replicating, has shifting colors for the mouse as it moves across the screen.

My idea was to have different layers: the dark background, the “blob”, the gradient, then a blur like the tutorial. The gradient wouldn’t show up against the dark background but when a white blob was beneath the gradient, then the colors would show up is my line of thinking. I’m currently at a point where it is simply the white blob and dark background. I’m wondering if this is even possible as I am thinking the issue is with the gradient’s blend modes interfering (although I don’t know if this is even the issue).

I’m also having issues having with safari. On chrome, I can get the smooth blob that tracks my mouse with a blur, however on safari, the blob either doesn’t appear or the tracking is off or the blob restarts it’s position every time I move my mouse. I know that different browsers require different things, but I was wondering if there are easier ways to make sure that both browsers can handle the site.

Also if you know another way of just having shifting colors for my blob while keeping the linear gradient that would be helpful too!

Here is my html, css, and javascript code. Thank you!

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

window.onpointermove = event => {
  const {
    clientX,
    clientY
  } = event;

  blob.animate({
    left: `${clientX}px`,
    top: `${clientY}px`
  }, {
    duration: 2500,
    fill: "forwards"
  });
};
body {
  background-color: #222020;
  height: 100vh;
  margin: 0;
  overflow: hidden;
  position: relative;
}

#gradient-color {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(50% 123.47% at 50% 50%, #00ff94 0%, #720059 100%), linear-gradient(121.28deg, #669600 0%, #ff0000 100%), linear-gradient(360deg, #0029ff 0%, #8fff00 100%), radial-gradient(100% 164.72% at 100% 100%, #6100ff 0%, #00ff57 100%), radial-gradient(100% 148.07% at 0% 0%, #fff500 0%, #51d500 100%);
  background-blend-mode: screen, color-dodge, overlay, difference, normal;
  z-index: 1;
  opacity: 0;
}

#blob {
  height: 34vmax;
  aspect-ratio: 1;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  background-color: white;
  mix-blend-mode: difference;
  opacity: 1;
  z-index: 2;
}

#blur {
  height: 100%;
  width: 100%;
  position: fixed;
  z-index: 3;
  backdrop-filter: blur(12vmax);
}
<div id="gradient-color"></div>
<div id="blob"></div>
<div id="blur"></div>
<section class="showcase">
  <nav class="navbar vertical-center line line-vertical"></nav>
</section>

Why is NPM called Node Package Manager when the packages aren’t necessarily written in node.js? [duplicate]

From what I understand, node packages that you can install with npm aren’t necessarily written in Node.js. For example, you can install node packages in many frontend languages like React or Angular, which don’t run node.js but Javascript instead. So are these node packages written in node.js or regular Javascript? Shouldn’t npm be called “jpm” (Javascript Package Manager) to make it more accurate?

ESLint adding global configuration for browser error?

Trying to add the browser using ESLint globals configuration as follows (eslint.config.js) per the documentation.

import eslint from "@eslint/js";
import globals from "globals";

export default [
    // apply recommended rules to JS files
    
    {
        languageOptions: {
            globals: {
                ...globals.browser
            }
        }
    },
    {

        files: ["**/*.js", "**/*.cjs", "**/*.mjs"],
        rules: eslint.configs.recommended.rules
    },
    {
        ignores: ["rollup.config.js", "web-test-runner.config.js", "src/index.bundle.js"]
    }
]

When added it produces this error.


Oops! Something went wrong! :(

ESLint: 9.11.1

TypeError: Key "languageOptions": Key "globals": Global "AudioWorkletGlobalScope " has leading or trailing whitespace.
    at new Config (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/config/config.js:211:23)
    at [finalizeConfig] (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/config/flat-config-array.js:216:16)
    at FlatConfigArray.getConfigWithStatus (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@eslint/config-array/dist/cjs/index.cjs:1102:55)
    at FlatConfigArray.getConfig (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@eslint/config-array/dist/cjs/index.cjs:1120:15)
    at /Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/eslint/eslint-helpers.js:346:56
    at Array.reduce (<anonymous>)
    at /Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/eslint/eslint-helpers.js:333:36
    at /Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/eslint/lib/eslint/eslint-helpers.js:296:32
    at Object.isAppliedFilter (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@nodelib/fs.walk/out/readers/common.js:12:31)
    at AsyncReader._handleEntry (/Users/oleersoy/Temp/Remove/fs-javascript-starter/node_modules/@nodelib/fs.walk/out/readers/async.js:86:20)

Any ideas?

How does React update only the parts of the DOM that need updating?

How is React able to update only the parts of the DOM that require updating (because they’ve changed) as opposed to re-rendering the entire DOM?

From what I understand, regular HTML/Javascript web pages react to changes in the DOM by re-rendering the entire DOM. I also understand that React uses a virtual DOM to determine what has changed and what has not. It compares the previous state of the virtual DOM with the new one to determine what has changed and updates the real DOM to match the virtual DOM only on the nodes that have changed. I also understand that when transpiled, React code is converted to regular Javascript.

Putting this all together leads to the question above. If React just becomes regular Javascript after transpilation, then at run time, it’s the same situation as a regular HTML/Javascript web page. But this is said to render the entire DOM in response to any change in the DOM. So how does the code only update the parts of the DOM that need updating? The browser doesn’t know (nor would it care) that it used to be React code, so why should it handle the DOM any differently than a regular HTML/Javascript web page? Is there a way in plain Javascript to tell it to update only part of the DOM instead of re-rendering the entire DOM? Is that what a React application is doing after being transpiled to plain Javascript?

Is there a way to export namespace, custom html tag names and possibly invalid HTML from HTML element class or DOM?

I’d like to use the HTMLElement class to format my code for export using the toString() method. But the code that I want to export may or may not be valid HTML. I’d also like to be able to export with unsupported attributes.

The reason to do this is to get the formatting tabs and indentation correct and to allow the DOM to validate the HTML for everything except my use cases mentioned here.

Is it possible to use that class to export code that may not be valid HTML? The last time I checked it would not allow me to do that but I have reason to believe it may allow it now.

Examples of exported tags:

- <abc:div> 
- <mycustomtagname>
- <?php
- <abc:mytag unsupportedattribute="10">

The lines above represent:

- A tag with a namespace.  
- A custom tag not defined in the HTML spec  
- A php tag so that php can be wrapped around blocks of HTML.  
- A custom attribute 

What I’m trying to do is use the HTMLElement class to export to different languages. I like this class and using it would solve many issues around formatting and creating valid HTML. Having custom php tags might make it invalid HTML so I don’t know if the .toString() method would export it anyway. In the past incorrect or unsupported HTML was corrected when using toString().

Example of HTML to export:

<div>
  <input/>
</div>

Example of PHP / HTML to export:

<div>
  <?php 
     <input/>
  ?>
</div>

Example of XML to export:

<a:div>
  <b:input></b:input>
</a:div>

Example of HTML with user attributes (not using data names):

<div myattribute="10">
  
</div>

But if it can’t export those types of tags is there any recommendations for alternatives? It needs to be a generic export type of class. For example, there is the XMLDocument class that supports namespaces but that would export XML not HTML. There is the DOM and the DOMDocument objects and I’ve even seen some classes like shadow DOM.

My own suggestion to this problem would be export bodyElement.toString() but using valid tag name as tokens and then do a global search and replace. So there would be a valid HTML token for php like, <php> and it would be replaced with an actual php tag later, <?php.

How to decrypt C++ OpenSSL ChaCha20 from nodeJS?

I’m trying to decrypt data that have been encrypted using C++ OpenSSL ChaCha20 from Node.js, but standard Node.js crypto module doesn’t directly support ChaCha20 without Poly1305.

I have tried using the JsChaCha20 lib, it doesnt fail but the decrypted data is not correctly, the decrypt function return this: 'bAۄ���@��'

I’m trying to figure if its a problem with my code or with the JsChaCha20 lib or even a missmatch between the OpenSSL implementation and the lib.

// https://github.com/thesimj/js-chacha20/blob/master/src/jschacha20.js
import crypto     from 'crypto'
import JSChaCha20 from './jschacha20.js'

function decrypt(data, password)
{
    if (!data.length)
        return false

    // Generate a salt from the password
    const pwhash = crypto.createHash('sha256').update(password).digest()
    const salt   = Buffer.from(pwhash)

    const NONCE_SIZE = 12
    const KEY_SIZE   = 32

    // Derive key from password
    const key = crypto.createHash('sha256').update(password).digest()

    // Derive nonce
    const context = Buffer.concat([Buffer.from(password), salt])
    const hash    = crypto.createHash('sha256').update(context).digest()
    const nonce   = hash.slice(0, NONCE_SIZE)

    // Log values for comparison
    console.log('nkeyn', key.toString('base64'))
    console.log('nnoncen', nonce.toString('base64'))
    console.log('nsaltn', salt.toString('base64'))
    console.log('ncontextn', context.toString('base64'))

    try 
    {
        const decipher = new JSChaCha20(key, nonce)
        let decrypted  = decipher.decrypt(Buffer.from(data))
        decrypted      = Buffer.from(decrypted).toString('utf8')
        return decrypted
    } 
    catch (error)
    {
        console.error(error.message)
        return false
    }
}

let encrypted   = "b1OnS61xyC/D0Dc="
encrypted       = Buffer.from(encrypted, 'base64')
const decrypted = decrypt(encrypted, "password")

My C++ OpenSSL ChaCha20 implementation:

#include <openssl/sha.h>
#include <openssl/buffer.h>
#include <openssl/rand.h>
#include <openssl/evp.h>

bool encrypt(std::string& data, std::string& password)
{
    if (data.empty()) 
        return false;
    
    // Generate a salt from the password
    unsigned char pwhash[SHA256_DIGEST_LENGTH];
    SHA256(reinterpret_cast<const unsigned char*>(password.data()), password.size(), pwhash);
    std::vector<unsigned char> salt(pwhash, pwhash + 32);

    constexpr size_t NONCE_SIZE = 12;
    constexpr size_t KEY_SIZE = 32;

    // Derive key from password
    unsigned char key[KEY_SIZE];
    SHA256(reinterpret_cast<const unsigned char*>(password.data()), password.size(), key);

    // Derive nonce
    std::vector<unsigned char> context;
    context.reserve(password.size() + salt.size());
    context.insert(context.end(), password.begin(), password.end());
    context.insert(context.end(), salt.begin(), salt.end());
    
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256(context.data(), context.size(), hash);
    std::vector<unsigned char> nonce(hash, hash + NONCE_SIZE);
    
    // Encrypt with derived nonce
    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
    if (!ctx) return false;
    if (EVP_EncryptInit_ex(ctx, EVP_chacha20(), nullptr, key, nonce.data()) != 1) {
        EVP_CIPHER_CTX_free(ctx);
        return false;
    }

    std::vector<char> ciphertext(data.size(), 0);
    int ciphertextLen;
    if (EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char*>(ciphertext.data()), &ciphertextLen, 
                          reinterpret_cast<const unsigned char*>(data.data()), data.size()) != 1) {
        EVP_CIPHER_CTX_free(ctx);
        return false;
    }
    EVP_CIPHER_CTX_free(ctx);
    ciphertext.resize(ciphertextLen);

    // Print key, nonce, salt, and context in base64
    auto toBase64 = [](const unsigned char* data, size_t len) -> std::string {
        BIO* b64 = BIO_new(BIO_f_base64());
        BIO* bio = BIO_new(BIO_s_mem());
        bio = BIO_push(b64, bio);
        BIO_write(bio, data, len);
        BIO_flush(bio);
        BUF_MEM* bufferPtr;
        BIO_get_mem_ptr(bio, &bufferPtr);
        std::string result(bufferPtr->data, bufferPtr->length - 1); // Exclude the null terminator
        BIO_free_all(bio);
        return result;
    };

    std::cout << "nkeyn"     << toBase64(key, sizeof(key));
    std::cout << "nnoncen"   << toBase64(nonce.data(), nonce.size());
    std::cout << "nsaltn"    << toBase64(salt.data(), salt.size());
    std::cout << "ncontextn" << toBase64(context.data(), context.size());

    int encDataSize = 4 * ((data.length() + 2) / 3);
    std::vector<unsigned char> b64(encDataSize + 1); // +1 for the terminating null that EVP_EncodeBlock adds on
    EVP_EncodeBlock(b64.data(), reinterpret_cast<const unsigned char*>(ciphertext.data()), ciphertext.size());

    data = std::string(b64.begin(), b64.end());

    return true;
}


int main()
{
    std::string data     = "Hello World";
    std::string password = "password";
    encrypt(data, password);
}

key, nonce, salt, contenxt all them matches the values from the C++ function.

Im derivating the nonce from the password, so i wouldnt need to append it to the cipher, i know this is not secure, but im trying to not increase the data size, this is why im trying ChaCha20 over Poly1305 as Poly1305 also appends a tag.

Take table header text to prepend on table body cell

I have a table and need to get it responsive. What I need to do is to take each column’s header’s text to prepend on this column’s body cell by using Jquery.

Problem: I am getting all 3 headers text prepend on all table body cells! ( It should be: CountryAlfreds, but I get CountryContactCompanyAlfreds, for example)
Please take a look at my sample below and direct me how to take each column’s header’s text to prepend on this column’s body cell.
Any help would be appreciated!

$('thead tr th').each( function(e) {
var headerText = $(this).html();
console.log("Header " + headerText);

 $(`table tbody tr td`).prepend("<span>" + headerText + "</span>")

})
span {
color: red;
font-weight: 700
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table>
 <thead>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  </thead>
  <tbody>
    
 
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr> 
  </tbody>
</table>

JS console logging using styles (%c) adds unintended line breaks

I’m working on some debugging logging prettification and I noticed that when you do longer chunks of styled text, the console tends to add line breaks. I wonder if I can prevent this behavior. Maybe there’s something in the styles that could prevent it elegantly?

Here’s an example:

const cssHeadField = `border-bottom: 1px solid grey;font-family: 'Courier New',monospace;font-weight: 600;font-size: 1.2em;background-color: Orange; color: black`;
const cssError = `background-color: Red; color: black`;

console.log(`no formatting at all %c and now head field kicks in and now it stops: %c and now a bunch of text that has no formatting, oop! %can error here%c some more text with no for... %coh, another error!%c`, cssHeadField, "", cssError, "", cssError, "")
console.log(`no formatting at all %c and now head field kicks in and now it stops: %c and now a bunch of text that has no formatting, oop! %can error here, maybe a longer error description too something that would be multiline or something right?%c some more text with no for... %coh, another error! This one is supposed to be long too just to test it out I guess%c`, cssHeadField, "", cssError, "", cssError, "");

enter image description here

File download from Javascript not working but OK from direct HTML link

I am trying to download a file from an ESP32 which is running the PsychicHTTP webserver. For testing, this is just a fixed .CSV file. In HTML:

<div>
<button type="button" onclick="saveFile()">Save file</button>
</div>

In the associated Javascript:

function saveFile() {
  var xhr = new XMLHttpRequest();
  console.log("SAVING FILE");
  xhr.open("GET", "/saveFile", true);
  xhr.send();
}

In the ESP32 code, in the setup for the webserver:

server.on("/saveFile", [](PsychicRequest *request) {
  Serial.println("SAVE FILE REQUEST");
  String filename = "/results/sample.csv";
  PsychicFileResponse response(request, LittleFS, filename, (String&)("text/csv"), true);

  return response.send();
});

I have also made a small mod to the PsychicHTTP webserver code to include “text/csv” as a MIME type.

When this is all running, the webserver receives the GET request for the download, I can see this in the Firefox console and in the ESP32 serial message. However the file doesn’t download. ESP32 is at 192.168.0.136 so if I type in 192.168.0.136/saveFile directly in the browser address bar then the file is downloaded and saved.
I have seen a few different examples of file downloads in Javascript and they all seem to use either “FETCH” or some form of HTML. Something like this:

function downloadFile(url, fileName) {
  fetch(url, { method: 'get', mode: 'no-cors', referrerPolicy: 'no-referrer' })
    .then(res => res.blob())
    .then(res => {
      const aElement = document.createElement('a');
      aElement.setAttribute('download', fileName);
      const href = URL.createObjectURL(res);
      aElement.href = href;
      aElement.setAttribute('target', '_blank');
      aElement.click();
      URL.revokeObjectURL(href);
    });
};

I can also try the simple HTML version of this when I get time – just using tag with download attribute – as my requirement is pretty simple.

So my two questions:

  • Why does a direct addressing to the download link work from the address bar but the Javascript above does not work?
  • If I use the FETCH example below, do I retain the same code in the ESP32 to respond or is something different required?

Marked JS Input Param defined as null Err

I am building an API for my site that grabs an MD file based off URL param (?key=test.md) and then renders it with Marked.js.

My problem is after the API grabs the file and trys to render it i get this error

marked.min.js:6 Uncaught Error: marked(): input parameter is undefined or null
Please report this to https://github.com/markedjs/marked.
    at ie.parse (marked.min.js:6:34386)
    at Object.oe (marked.min.js:6:35545)
    at main.js:14:30

I’ve checked my variables and network and don’t have an idea of what is undefined. Here is m current API code and simple workings.

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);

let article = urlParams.get('key');
let pre = `https://mrchaoticx.github.io/Chaotic-Club/articles/${article}`;

let contentID = document.getElementById("content");
let content;
fetch(pre)
  .then(response => response.text())
  .then(data => {content = data})
  .then(data => console.log(content))

contentID.innerHTML = marked.parse(content);
        <div class="content" id="content">
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/14.1.2/marked.min.js" integrity="sha512-bXyBT2/sYjZg1D7ykDS6eJSE4DFDVPJHvbRAfdfYKr6IusrCz7wAmSm36vz9G8zMob25Rvqu90vft3JI71ygcQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>        

How to control the ticks labels major or minor?

I have not been able to control the labels from scales/x/ticks/major or minor.
Here is a simple code to illustrate the problem.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Major Ticks in Bold, Minor Ticks Normal</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

</head>
<body>

<canvas id="myChart"></canvas>

<script>
    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['2023-10-01', '2023-10-02', '2023-10-03', '2023-10-04', '2023-10-05'],
            datasets: [{
                label: 'Sample Data',
                data: [10, 20, 15, 25, 18],
                borderColor: 'blue',
                borderWidth: 2,
                fill: false,
            }]
        },
        options: {
            scales: {
                x: {
                    type: 'time',
                    time: {
                        unit: 'hour',
                        displayFormats: {
                            day: 'YYYY/MM/DD',
                            hour: 'HH:MM'
                        }
                    },
                    ticks: {
                        major: {
                            enabled: true,
                            font: {
                                weight: 'bold'  // Major ticks in bold
                            }
                        },
                        minor: {
                            font: {
                                weight: 'normal'  // Minor ticks in normal weight
                            }
                        }
                    }
                },
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>

</body>
</html>

enter image description here

I expect to have date in bold and hours with normal font. The documentation is not enough detailled on this feature.

Am I missing something ?

How should i style the content using Tailwind CSS?

I’m trying to style my header item container and inside that i have a home icon and i’m pulling that icon from the header page and everything is working like if i try to give header or p tag but when i’m styling the icon or any p tag etc. i’m not getting any results on the webpage i think it must be tailwind css problem but i’m not able to figure out what is it.

This is the Header.js

import {
    BadgeCheckIcon,
    CollectionIcon,
    HomeIcon,
    LightningBoltIcon,
    SearchIcon,
    UserIcon,
} from "@heroicons/react/24/outline";
import Image from "next/image";
import HeaderItem from "./HeaderItem";

function Header() {
  return (
    <header className="">
        <div>
            {/* This is for icons that i'm using on the components section */}
            <HeaderItem title ='HOME' Icon = {HomeIcon}/>
        </div>
        {/* This is the logo image we are going to add in header component */}
        <Image
            className="object-contain"
            src='/images/hulu.png' 
            width={200} 
            height={100}
        />
    </header>
  )
}

export default Header

and this is HeaderItem.js

function HeaderItem({ Icon, title }) {
  return (
    <div>
        <Icon className='h-8 mb-1'/>
        <p className="opacity-0 hover:opacity-100 tracking-widest">{title}</p>
    </div>
  );
}

export default HeaderItem;

you can see ii was styling using tailwind but it is not reflecting on my webpage.

App script to copy all data from Workbook A to Workbook B, appending to first blank row not working correctly

I modified a script I found to copy data from the ‘Data’ tab of workbook A to the ‘LookerData’ tab of workbook B, but need it to add continuously to the ‘LookerData’ tab with no blank rows between). Now it’s adding it thousands rows below the first entry! (Data was 8000+ rows). It seemed to be working when testing with data that filled every cell, but fails with my actual data format which has random empty cells. Is there a way to get getLastRow to look only at Col A? Attaching some mock data to show format. Data will be a different size each month which is why I wasn’t specifying ranges.

The script also is adding thousands of rows causing the “you’ve hit your limit” error. This makes me think this is not the right approach when copying large data list like this? Assuming it must be creating very large arrays.

data format

`// https://stackoverflow.com/questions/48691872/google-apps-script-copy-data-to-different-worksheet-and-append
// Copies to Row 2 of target sheet the first time  and then appends to first blank row.

function CopyRange() {
 var sss = SpreadsheetApp.openById(’SpreadsheetA ID’); //replace with source ID
 var ss = sss.getSheetByName('Data'); //replace with source Sheet tab name
 var range = ss.getRange(2, 1, ss.getLastRow(), ss.getLastColumn()); //assign the range you want to copy
 var data = range.getValues();

// Logger.log(data);

 var tss = SpreadsheetApp.openById(‘SpreadsheetB ID’); //replace with destination ID
 var ts = tss.getSheetByName('LookerData'); //replace with destination Sheet tab name

 ts.getRange(ts.getLastRow()+1, 1,ss.getLastRow(), ss.getLastColumn()).setValues(data); 

}
`