D3 – Enter(), Exit(), Update() function doesnt work correctly

I want to be able to adjust the data of my D3 chart and update the chart. To do this, I tried to delete the old “slice” elements and then update them.

My problem is that the wrong “slices” elements are deleted (not the missing ones) and the same, that are delete will be opened again (picture, green should be delete and red will be deleted). I want the “g”, “path” and “text” elements to be deleted in “g.slice” and then the new elements will be created with the new data. My delete and update code will be find in the “Enter(), Update, Exit()” comment section.

enter image description here

// Data
const data1 = {
  "name": "TOPICS",
  "children": [{
    "name": "Topic A",
    "children": [{
      "name": "Sub A1",
      "size": 4
    }, {
      "name": "Sub A2",
      "size": 4
    }]
  }, {
    "name": "Topic B",
    "children": [{
      "name": "Sub B1",
      "size": 3
    }, {
      "name": "Sub B2",
      "size": 3
    }, {
      "name": "Sub B3",
      "size": 3
    }]
  }, {
    "name": "Topic C",
    "children": [{
      "name": "Sub A3",
      "size": 4
    }, {
      "name": "Sub A4",
      "size": 4
    }]
  }]
};

const data2 = {
  "name": "TOPICS",
  "children": [{
    "name": "Topic A",
    "children": [{
      "name": "Sub A1",
      "size": 4
    }, {
      "name": "Sub A2",
      "size": 4
    }]
  }, {
    "name": "Topic B",
    "children": [{
      "name": "Sub B1",
      "size": 3
    }, {
      "name": "Sub B2",
      "size": 3
    }, {
      "name": "Sub B3",
      "size": 3
    }]
  }]
};

//-------------------------------------------------------------------------------------------            
// Declare variables
var i_region_static_id = "sunburst",
  parentDiv = document.getElementById(i_region_static_id),
  width = parentDiv.clientWidth,
  height = 450,
  root,
  rootDepth,
  x,
  y,
  arc,
  middleArcLine,
  middleAngle,
  color = d3.scaleOrdinal(d3.schemeCategory20);
maxRadius = (Math.min(width, height) / 2) - 5;

const partition = d3.partition();
//-----------------------------------------------------------------------------------
// SVG-Element
var svg = d3.select('#' + i_region_static_id).append('svg')
  .style('width', width)
  .style('height', height)
  .attr('viewBox', `${-width / 2} ${-height / 2} ${width} ${height}`)
  .on('dblclick', d => {
    if (event.detail === 2) focusOn() // Double click
  });
//-----------------------------------------------------------------------------------
// X-Scale
x = d3.scaleLinear()
  .range([0, 2 * Math.PI])
  .clamp(true);

//-----------------------------------------------------------------------------------
// Y-Scale
y = d3.scaleSqrt()
  .range([maxRadius * .1, maxRadius]);

//-----------------------------------------------------------------------------------
// Create Arc generator
arc = d3.arc()
  .startAngle(d => x(d.x0))
  .endAngle(d => x(d.x1))
  .innerRadius(d => Math.max(0, y(d.y0)))
  .outerRadius(d => Math.max(0, y(d.y1)))

//-----------------------------------------------------------------------------------
middleArcLine = d => {
  const halfPi = Math.PI / 2;
  const angles = [x(d.x0) - halfPi, x(d.x1) - halfPi];
  const r = Math.max(0, (y(d.y0) + y(d.y1)) / 2);

  const middleAngle = (angles[1] + angles[0]) / 2;
  const invertDirection = middleAngle > 0 && middleAngle < Math.PI; // On lower quadrants write text ccw
  if (invertDirection) {
    angles.reverse();
  }

  const path = d3.path();
  path.arc(0, 0, r, angles[0], angles[1], invertDirection);
  return path.toString();
}

//-------------------------------------------------------------------------------------------
// Check if node in depth
function maxDepth(d) {
  if (rootDepth == undefined) { // If user clicks next to sun = root undefined
    rootDepth = 0;
  }
  return ((d.depth - rootDepth) < 2);
}

//-------------------------------------------------------------------------------------------
function focusOn(d = {
  x0: 0,
  x1: 1,
  y0: 0,
  y1: 1
}) {
  // Reset to top-level if no data point specified

  // Activate top-level node if no data point specified 
  if (d.data == undefined) {
    svg.selectAll(".slice")
      .filter(d => d.parent == undefined && d.children != undefined)
      .each(function(d) {
        activateNode(d);
      });
  }

  root = d; // Root-node
  rootDepth = root.depth; // Root node depth for maxDepth(d)

  const transition = svg.transition()
    .duration(750)
    .tween('scale', () => {
      const xd = d3.interpolate(x.domain(), [d.x0, d.x1]),
        yd = d3.interpolate(y.domain(), [d.y0, 1]);
      return t => {
        x.domain(xd(t));
        y.domain(yd(t));
      };
    });

  transition.selectAll('.slice')
    .attr('display', d => maxDepth(d) ? null : 'none'); // Display nodes only in depth for transition

  transition.selectAll('path.main-arc')
    .filter(d => maxDepth(d))
    .attrTween('d', d => () => arc(d));

  transition.selectAll('path.hidden-arc')
    .filter(d => maxDepth(d))
    .attrTween('d', d => () => middleArcLine(d));

  transition.selectAll('text')
    .filter(d => maxDepth(d))
    .attrTween('display', d => () => textFits(d) ? null : 'none'); // Display text only in depth

  moveStackToFront(d);

  // Foreground nodes -> inner nodes higher than outer nodes 
  function moveStackToFront(elD) {
    svg.selectAll('.slice').filter(d => d === elD)
      .each(function(d) {
        this.parentNode.appendChild(this);
        if (d.parent) {
          moveStackToFront(d.parent);
        }
      })
  }
}

//-------------------------------------------------------------------------------------------
// Initialize and Update sun 
function sun(pData) {
  root = d3.hierarchy(pData); //set data

  root.sum(d =>
    (d.children == undefined) ? ((d.size == undefined) ? 1 : d.size) : 0 //parent value defined by childrens values
  );

  const slice = svg.selectAll('g.slice')
    .data(
      partition(root)
      .descendants()
    );

  slice.exit().remove();
  //-------------------------------------------------------------------------------------------
  // Enter(), Udpate, Exit()
  const newSlice = slice.enter()
    .append('g').attr('class', 'slice')
    .attr('display', d => d.depth < 2 ? null : 'none') // Hide levels lower depth
    .on('dblclick', d => {
      focusOn(d);
    })
    .append('path')
    .attr('class', 'main-arc')
    .style('fill', d => (d.data.color == undefined) ? color((d.children ? d : d.parent).data.name) : d.data.color) //set source color, otherwise default color
    .attr('d', arc)
    .append('path')
    .attr('class', 'hidden-arc')
    .attr('id', (_, i) => `hiddenArc${i}`)
    .attr('d', middleArcLine)

  const text = newSlice.append('text')
    .attr('display', d => d ? null : 'none'); // Hide text on lower levels

  text.append('textPath')
    .attr('startOffset', '50%')
    .attr('xlink:href', (_, i) => `#hiddenArc${i}`)
    .text(d => d.data.name) // Set text in sector 
    .attr('fill', d => 'black');

  // Delete Elements
  slice.exit().remove();
}

//-------------------------------------------------------------------------------------------

sun(data1)

let i = 0;
d3.interval(() => {
  if (i++ % 2 === 0) {
    console.log("data2")
    sun(data2);
  } else {
    console.log("data1")
    sun(data1);
  }

}, 4000)
.slice {
  cursor: pointer;
}

.slice .main-arc {
  stroke: #fff;
  stroke-width: 1px;
}

.slice .hidden-arc {
  fill: none;
}

.slice text {
  pointer-events: none;
  text-anchor: middle;
}
<div id="sunburst"></div>
<script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script>
<script src="https://unpkg.com/d3fc" charset="utf-8"></script>

nuxt-auth cannot get token data using refresh provider

I have some trouble with login functionality in Nuxt 3.

I have installed a package @sidebase/nuxt-auth for user Authentication.
These are my configurations in file nuxt.config.ts

auth: {
    globalAppMiddleware: true,
    baseURL: backendUrl,
    provider: {
      type: "refresh",
      endpoints: {
        signIn: { path: "/login/", method: "post" },
        signOut: { path: "/logout/", method: "get" },
        signUp: { path: "/register/", method: "post" },
        refresh: { path: "/refresh/", method: "post" },
        getSession: false,
      },
      pages: {
        login: "/login",
        register: "/register",
      },
      token: {
        signInResponseTokenPointer: "/access",
      },
      refreshToken: { signInResponseRefreshTokenPointer: "/refresh" },
    },

    enableSessionRefreshPeriodically: 5000,
    enableSessionRefreshOnWindowFocus: true,
    globalMiddlewareOptions: {
      allow404WithoutAuth: true, // Defines if the 404 page will be accessible while unauthenticated
      addDefaultCallbackUrl: "/", // Where authenticated user will be redirected to by default
    },
  },

This is the code for getting my token in file: server/api/auth/token.get.ts

import { getToken } from "#auth";
export default eventHandler(async (event) => {
  const token = await getToken({ event, cookieName: "auth" });
  console.log(token);
  return token || "no token present";
});

page code for printing the token:

<script setup lang="ts">
definePageMeta({
    auth : false,
})
const headers = useRequestHeaders(['cookie'])
const {data : token} = await useFetch('/api/auth/token', {headers});
</script>
<template>
    <pre>
        {{ token }}
    </pre>
</template>

My logic for logging in the user:

definePageMeta({
  layout: "front",
  auth: {
    unauthenticatedOnly: true,
    navigateAuthenticatedTo: '/token',
  }
});

const loginWithCredentials = async () => {
    try {
      let res = await signIn(
        { ...formData },
        { callbackUrl: '/token' } // Where the user will be redirected after a successiful login
      )
      console.log(res);
    } catch (error) {
      console.log("error", error);
    } 
}

I have to mention that I am using a custom backend to return JSON data with JWT token properties “access” and “refresh”.

So, If I send a post request to an url backEndUrl/login/ with correct user credentials I get a response like this:

JsonResponse

I have tried to put the access token to https://jwt.io/ which got me this result:

JWTResponse

I am expecting the getToken() to return me the payload data, however it returns null.

What could be the problem?

Ant design 4 does not work anymore after running npm install

I encounter an error with antd 4.12.3 and react 17.0.2 since a new generation of my node_module.

I didn’t have run npm install into my project since a long time,
After having delete my node_modules, package-lock, clean-cache
I run npm install, since then I have encountered lots of errors from antd
I didn’t change any version of any package in my package-json
has ant made an update on his 4x version ?
I don’t know if i have to fix all the error by myself into the project or if i can fix it by updating/downgrading a package ?
I also have a lot of css rules which no longer works
I use react-app-rewired

Thanks

My package.json :


 "dependencies": {  
    "antd": "^4.12.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.1",
    "js-file-download": "^0.4.12",
    "aphrodite": "^2.4.0",
    "less": "^3.13.1",
    "axios": "^0.19.2",
    "bizcharts": "^4.1.7",
    "chroma-js": "^2.1.0",
    "connected-react-router": "^6.8.0",
    "exceljs": "^4.2.0",
    "file-saver": "^2.0.5",
    "highlight.js": "^10.6.0",
    "lodash": "^4.17.20",
    "jspdf": "^2.3.0",
    "jspdf-autotable": "^3.5.14",
    "localforage": "^1.9.0",
    "md5": "^2.3.0",
    "re-resizable": "^6.9.0",
    "react-base-table": "^1.12.0",
    "react-color": "^2.19.3",
    "react-helmet": "^6.1.0",
    "react-hotkeys-hook": "^2.4.1",
    "react-ionicons": "^4.2.1",
    "react-router-dom": "^5.2.0",
    "react-sortable-hoc": "^2.0.0",
    "react-transition-group": "^4.4.1",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "slugify": "^1.4.6",
    "xml-js": "^1.6.11"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "release": "standard-version --release-as patch",
    "release-as": "standard-version --release-as",
    "build": "node ./scripts/buildVersion.js && GENERATE_SOURCEMAP=false node node_modules/.bin/react-app-rewired --max_old_space_size=4096 build",
    "build-win": "node ./scripts/buildVersion.js && set "GENERATE_SOURCEMAP=false" && node node_modules/react-app-rewired/bin --max_old_space_size=4096 build",
    "test": "react-app-rewired test --watchAll",
    "eject": "react-app-rewired eject",
    "deploy": "bash ./scripts/ftp_send.sh",
    "server": "node-env-run server --exec nodemon",
    "dev": "run-p server start",
    "analyze": "source-map-explorer build/static/js/4.b01fcf9f.chunk.js"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "react-app-rewired": "^2.1.8",
    "less-loader": "^7.0.0",
    "antd-theme-generator": "^1.2.11",
    "antd-dayjs-webpack-plugin": "^1.0.6",
    "antd-theme-webpack-plugin": "^1.3.9",
    "babel-plugin-import": "^1.13.3",
    "customize-cra": "^1.0.0",
    "@hot-loader/react-dom": "^17.0.2"
    }

My config-overides.js :

const path = require("path");
const fs = require("fs");
const {
  override,
  fixBabelImports,
  addLessLoader,
  addWebpackPlugin,
  addWebpackAlias,
} = require("customize-cra");
const { getThemeVariables } = require("antd/dist/theme");
const AntDesignThemePlugin = require("antd-theme-webpack-plugin");
const AntdDayjsWebpackPlugin = require("antd-dayjs-webpack-plugin");

const { getLessVars } = require("antd-theme-generator");

const defaultVars = getLessVars(
  "./node_modules/antd/lib/style/themes/default.less"
);

//CTI custom common variables
const themeVariables = getLessVars(
  path.join(__dirname, "./src/styles/_variables.less")
);

//Default dark vars mixed with custom CTI dark colors
const darkVars = {
  ...getLessVars("./node_modules/antd/lib/style/themes/dark.less"),
  "@primary-color": defaultVars["@primary-color"],
  ...getLessVars(path.join(__dirname, "./src/styles/themes/_darkVariables.less")),
};

//Default light vars mixed with custom CTI light vars
const lightVars = {
  ...getLessVars("./node_modules/antd/lib/style/themes/compact.less"),
  "@primary-color": defaultVars["@primary-color"],
  ...getLessVars(path.join(__dirname, "./src/styles/themes/_lightVariables.less")),
};

//Write mixed vars in JSON files (used to dynamically)
fs.writeFileSync("./src/dark.json", JSON.stringify(darkVars));
fs.writeFileSync("./src/light.json", JSON.stringify(lightVars));
fs.writeFileSync("./src/theme.json", JSON.stringify(themeVariables));

const options = {
  stylesDir: path.join(__dirname, "./src"),
  antDir: path.join(__dirname, "./node_modules/antd"),
  varFile: path.join(__dirname, "./src/styles/_variables.less"),
  themeVariables: Array.from(
    new Set([
      ...Object.keys(darkVars),
      ...Object.keys(lightVars),
      ...Object.keys(themeVariables),
    ])
  ),
  generateOnce: true, // generate color.less on each compilation
};

module.exports = override(
  fixBabelImports("import", {
    libraryName: "antd",
    libraryDirectory: "es",
    style: true,
  }),
  addWebpackAlias({
    ['@components']: path.resolve(__dirname, './src/components'),
    ['@helpers']: path.resolve(__dirname, './src/helpers'),
    ['@adapters']: path.resolve(__dirname, './src/helpers/adapters'),
    ['@api']: path.resolve(__dirname, './src/services/api'),
    ['@formatter']: path.resolve(__dirname, './src/helpers/formatter'),
    ['@localForage']: path.resolve(__dirname, './src/helpers/localForage'),
    ['@template']: path.resolve(__dirname, './src/helpers/template'),
    ['@utils']: path.resolve(__dirname, './src/helpers/utils'),
    ['@styles']: path.resolve(__dirname, './src/styles'),
    ['@actions']: path.resolve(__dirname, './src/redux/actions'),
    ['@reducers']: path.resolve(__dirname, './src/redux/reducers'),
    ['@redux']: path.resolve(__dirname, './src/redux/'),
    ['@dark']: path.resolve(__dirname, './src/dark.json'),
    ['@light']: path.resolve(__dirname, './src/light.json'),
    ['@Content']: path.resolve(__dirname, './src/components/Content'),
    ['@charts']: path.resolve(__dirname, './src/components/charts'),
    ['@Page']: path.resolve(__dirname, './src/components/Page'),
    ['@Settings']: path.resolve(__dirname, './src/components/Settings'),
    ['@shared']: path.resolve(__dirname, './src/components/shared'),
    ['@View']: path.resolve(__dirname, './src/components/View'),
    ['@services']: path.resolve(__dirname, './src/services'),
    ['@requests']: path.resolve(__dirname, './src/services/requests'),
  }),
  addWebpackPlugin(new AntDesignThemePlugin(options)),
  addWebpackPlugin(new AntdDayjsWebpackPlugin()),
  addLessLoader({
    lessOptions: {
      javascriptEnabled: true,
      modifyVars: {
        ...getThemeVariables({
          compact: true,
        }),
      },
    },
  })
);

Js error
Js error

I tried to downgrad or upgrade ant version
I tried to load one old package.json who was working and i encounter the same error
I tried to load a old stable version and reload the node module and encounter the same error
I tried to fix error manually, but there is a lot of error, like if i was having upgrade to ant 5x

How do I solve the discord bot Undici proxy authorization header not being cleared in cross-origin redirection on fetch error?

How do I solve the discord bot Undici proxy authorization header not being cleared in cross-origin redirection on fetch error? I install the discord.js source package, it says it was successful, but later when I give the node .app.js command, it says there is no discord.js package, I don’t know what I should do.

import { Client } from "discord.js"
const client = new Client({
      intents: ["GUILDS"]
})

Client.on("ready", () => {
    console.log("X Boots Active!")
})

client.login("TOKEN")

Running Apps Script function from Apps Script API

Hello everyone

I apologize in advance for the amount of “Apps Scripts” (AS for short). Keep in mind the difference between Apps Script projects (code.gs) and the Apps Script API.

The general idea is to be able to create AS projects, write functions inside and execute them, all from a ‘parent’ AS project.

After confirming that there was no AS-specific method for creating new AS projects (other than by hand), I recently managed to get the AS API working from within an AS project.

The projects.create method works great for creating new projects.

The projects.updateContent method works great for writing code inside newly created projects.

However, I’m having trouble using the script.run method to try and execute functions contained in new projects from the API

Here is how I tried to get it working:

function runScript() {

    var scriptId = 'target_script_id'
    var functionName = 'target_function_name';

    var accessToken = ScriptApp.getOAuthToken();

    var url = 'https://script.googleapis.com/v1/scripts/' + scriptId + ':run';

    var payload = {
        'function': functionName,
        'devMode': false
    };
  
    var options = {
        'method': 'post',
        'contentType': 'application/json',
        'payload': JSON.stringify(payload),
        'muteHttpExceptions': true,
        'headers': {
            'Authorization': 'Bearer ' + accessToken
         }
    };
  
    var response = UrlFetchApp.fetch(url, options);
    var responseData = JSON.parse(response.getContentText());
    Logger.log (responseData);
    return responseData; 
}  

and here is the error I received:

{
  "error": {
    "code": 500,
    "message": "Internal error encountered.",
    "status": "INTERNAL"
  }
}

node-red HTTP authentication through environmental variables

I want to perform a GET request to an API but I want to make sure the endpoint, username and password are managed as environmental variabled because my node application will have multiple environments (dev/test/production).

I have added the environmental variables on the flow.
enter image description here

Now I’m trying to set the correct attributes on the msg object to replace the values with the environmental variables.
enter image description here

It’s already working for the url but I’m not able to replace the username and password. I cannot find the correct attribute names anywhere in the docs.
I can imagine that a lot of people would have simular requirements when working with multiple-tier systems.

So what is in fact the correct way to achieve this?

msg.url = 
 env.get("MendixURL")
 + "/rest/shopfloorintegration/v1/message?PlantCode="
 + env.get("PlantCode");

msg.authentication = "basic";
msg.credentials = {
    username : env.get("MendixUsername"),
    password : env.get("MendixPassword")
};


return msg;

enter image description here

Resume polling after 286

Making a small game with HTMX and Go. I’m having HTMX poll the server and updating the state of the game every 1 second or on user input

<div class="game" hx-post="/tick" hx-trigger="every 1s, keydown[ (some keys here) ] from:body">
    {{ block "state" . }}
    <!-- state -->
    {{ end }}
</div>

When the game ends, I send 286 status code to stop the polling of “every” trigger, as mentioned here.

The user is given the option to restart the game, how can I resume the polling?

Note that moving the div inside the state block is not an option, because then user inputs reset the 1 second timer.

Is there another status code that can be sent? or even some custom JS to restart the polling?

Copy field to clipboard and keeping all formatting with Javascript

I’m using SharePoint pages and script editor to build a copy button for quick copy/pasting of templates used on SharePoint. The current code I’m using works perfectly except it doesn’t copy over for formatting.

For the context of this particular code, I followed these steps to build it.

  1. Create a SharePoint page with a body of text.
  2. Publish the page
  3. Right-click on that page to inspect it using Google’s Developer Console (seen here)
  4. Copy the outerHTML for the div that the text field sets in
  5. Pull the DIV ID from that code
  6. Edit the SharePoint Page again (seen here)
  7. Add DIV ID to JavaScript code into Script Editor
  8. Publish page
  9. Copy button works (seen here)

Using the JavaScript code below, I was hoping the copy function would copy over the formatting of the text in the SharePoint field.

Fair warning: I do not know anything about JavaScript. Someone was able to build this code for me, and I only know a little about how the code works outside of what I’ve displayed here. I don’t know where to begin troubleshooting, and when I research other coding, I don’t know where to begin with adding modifications to this code. I’m sorry in advance if I need some handholding.

My impression is that there is only a line or two of code, at most, that I can add to the existing code so that it keeps formatting like text size, bold, underline, hyperlinks, etc.

Any help with this would be greatly appreciated.

function myFunction(divId) {
  const copyDiv = document.getElementById(divId);

  if (copyDiv) {
    const textToCopy = copyDiv.innerText;
    navigator.clipboard.writeText(textToCopy)
      .then(() => {
        let tooltip = document.getElementById("myTooltip");
        tooltip.innerHTML = "Copied";
        setInterval(() => {
          tooltip.innerHTML = "Copy Template"
        }, 1000);
      })
      .catch(err => {
        console.error('Could not copy text: ', err);
      });
  } else {
    console.error('Element to copy from could not be found');
  }
}
<div>
  <button onclick="myFunction('2ed477e2-32d7-4f46-a4a9-0a55cdba22f5')" onmouseout="outFunc()">
    <span class="tooltiptext" id="myTooltip">Copy Template</span>
  </button>
</div>

Pixelation Javascript

How can i improve the code, so instead of pixelating the whole image, it pixelate only the area where mouse has clicked left button? Ability to do it in multiple places it the most important.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pixelate Image</title>
  <style>
    canvas {
      border: 1px solid black;
      cursor: crosshair;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="2000" height="2000"></canvas>
  <script>
    var canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d'),
      img = new Image();

    ctx.mozImageSmoothingEnabled = false;
    ctx.webkitImageSmoothingEnabled = false;
    ctx.imageSmoothingEnabled = false;

    img.src = 'obraz.jpg';
    img.onload = function() {
      pixelate();
    };

    function pixelate(v) {

      var size = v ? v * 0.01 : 1,
        w = canvas.width * size,
        h = canvas.height * size;

      ctx.drawImage(img, 0, 0, w, h);

      ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);

    }

    function focus(v) {

      var size = v * 0.01,
        w = canvas.width * size,
        h = canvas.height * size;

      ctx.drawImage(img, 0, 0, w, h);

      ctx.drawImage(canvas, 0, 0, w, h, 0, 0, canvas.width, canvas.height);

    }

    function mouseoverHandler() {
      pixelate(5);
    }

    function mouseoutHandler() {
      focus(100);
    }

    canvas.addEventListener('mouseover', mouseoverHandler, false);
    canvas.addEventListener('mouseout', mouseoutHandler, false);
  </script>
</body>

</html>

Instead of handling mouseover and mouseout events, I tried using mousedown and mouseup. No effects.

Using Unescaped Elasticsearch Regular Expressions from Front-End to Back-End in JavaScript

I’m working on a front-end JavaScript application where users can input strings that often include regular expressions. However, I’ve encountered an issue with automatic escaping of backslashes (). For instance, when a user inputs \a, it automatically transforms into \\\a.

Using .replace(“\”, “\”) seems to correct it to \\a, but this solution doesn’t hold up for more complex patterns. Consider the regular expression 192\.\d\+\.\d\+\.\d\+. Each time it’s processed, the backslashes multiply, turning it into 192\\.\\d\\+\\.\\d\\+\\.\\d\\+, which is not what I intended. While .replace(/\\/g, “\”) addresses this issue, it incorrectly alters inputs like \a to \\a, diverging from the original input.

Is there a consistent method to handle this scenario in JavaScript, ensuring that strings, especially those containing regular expressions with backslashes, are preserved accurately without unintended escaping?

This situation is particularly problematic when these strings are used in backend services or databases where the exact pattern is essential for operations like querying in Elasticsearch. I’m looking for a solution that maintains the integrity of the original user input across processes.

I have attempted various .replace() methods and even tried using String.raw to address automatic escaping of backslashes in strings, especially those representing regular expressions, in a front-end JavaScript context. Unfortunately, these efforts have not resolved the issue, and I’ve been struggling with this all day.

I’m reaching out for assistance after spending the entire day trying to find a solution without success.

Pause the animation of all html cards when the video popup is opened or when the play button on the video is clicked

I have two cards a small card which contain the video and another is bigger card which contain the title and description. Small card is nested inside the bigger cards. What i want is when ever i play the video of any card (in popup box or without popup box) the animation(movement) of all cards should be stop. And also why the last card not fully appear its half part is missing.
Please review my code and help me to achieve the result.

HTML

<div class="container">
  <!-- Cards will be dynamically generated here -->
  <!-- Example card -->
  <div class="card">
    <div class="video-card">
      <video controls>
        <source src="https://cdn.pixabay.com/vimeo/912684284/bird-200427.mp4?width=1280&hash=67fef5d5bd129d65e1bb235d5af18c429fd99732" type="video/mp4">
        Your browser does not support the video tag.
      </video>
    </div>
    <div class="review">
      <h2>Title 1</h2>
      <p>Description 1</p>
    </div>
    <div class="company-info">
      <h3>Company Name 1</h3>
    </div>
    <div class="arrow-down"></div>
  </div>
  <!-- End of example card -->

      <!-- Example card -->
  <div class="card">
    <div class="video-card">
      <video controls>
        <source src="https://cdn.pixabay.com/vimeo/912684284/bird-200427.mp4?width=1280&hash=67fef5d5bd129d65e1bb235d5af18c429fd99732" type="video/mp4">
        Your browser does not support the video tag.
      </video>
    </div>
    <div class="review">
      <h2>Title 1</h2>
      <p>Description 1</p>
    </div>
    <div class="company-info">
      <h3>Company Name 1</h3>
    </div>
    <div class="arrow-down"></div>
  </div>
  <!-- End of example card -->


      <!-- Example card -->
  <div class="card">
    <div class="video-card">
      <video controls>
        <source src="https://cdn.pixabay.com/vimeo/912684284/bird-200427.mp4?width=1280&hash=67fef5d5bd129d65e1bb235d5af18c429fd99732" type="video/mp4">
        Your browser does not support the video tag.
      </video>
    </div>
    <div class="review">
      <h2>Title 1</h2>
      <p>Description 1</p>
    </div>
    <div class="company-info">
      <h3>Company Name 1</h3>
    </div>
    <div class="arrow-down"></div>
  </div>
  <!-- End of example card -->


      <!-- Example card -->
  <div class="card">
    <div class="video-card">
      <video controls>
        <source src="https://cdn.pixabay.com/vimeo/912684284/bird-200427.mp4?width=1280&hash=67fef5d5bd129d65e1bb235d5af18c429fd99732" type="video/mp4">
        Your browser does not support the video tag.
      </video>
    </div>
    <div class="review">
      <h2>Title 1</h2>
      <p>Description 1</p>
    </div>
    <div class="company-info">
      <h3>Company Name 1</h3>
    </div>
    <div class="arrow-down"></div>
  </div>
  <!-- End of example card -->


      <!-- Example card -->
  <div class="card">
    <div class="video-card">
      <video controls>
        <source src="https://cdn.pixabay.com/vimeo/912684284/bird-200427.mp4?width=1280&hash=67fef5d5bd129d65e1bb235d5af18c429fd99732" type="video/mp4">
        Your browser does not support the video tag.
      </video>
    </div>
    <div class="review">
      <h2>Title 1</h2>
      <p>Description 1</p>
    </div>
    <div class="company-info">
      <h3>Company Name 1</h3>
    </div>
    <div class="arrow-down"></div>
  </div>
  <!-- End of example card -->

      <!-- Example card -->
  <div class="card">
    <div class="video-card">
      <video controls>
        <source src="https://cdn.pixabay.com/vimeo/912684284/bird-200427.mp4?width=1280&hash=67fef5d5bd129d65e1bb235d5af18c429fd99732" type="video/mp4">
        Your browser does not support the video tag.
      </video>
    </div>
    <div class="review">
      <h2>Title 1</h2>
      <p>Description 1</p>
    </div>
    <div class="company-info">
      <h3>Company Name 1</h3>
    </div>
    <div class="arrow-down"></div>
  </div>
  <!-- End of example card -->
</div>

<div class="video-popup">
  <div class="video-popup-content">
    <video controls></video>
    <button class="close-popup">Close</button>
  </div>
</div>

<div class="overlay"></div>

CSS

body, html {
  overflow-x: hidden;
}

.container {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: hidden;
  overflow-y: hidden;
  width: calc(100% + 380px);
  margin-left: -20px;
  animation: slide 20s linear infinite;
}

.card {
  flex: 0 0 auto;
  width: 360px;
  background-color: #f0f0f0;
  border-radius: 15px;
  margin-right: 20px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: border 0.3s;
}

.review {
  margin-top: 10px;
}

.video-card {
  border-radius: 10px;
  overflow: hidden;
}

.video-card video {
  width: 100%;
  border-radius: 10px;
}

.company-info {
  text-align: center;
  margin-top: 20px;
}

.arrow-down {
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-top: 15px solid #e0e0e0;
  position: absolute;
  bottom: -20px;
  left: calc(50% - 10px);
}

.card:hover {
  border: 2px solid #007bff;
  cursor: pointer;
}

.card:hover ~ .card {
  animation-play-state: paused;
}

@keyframes slide {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(-100%);
  }
}

.video-popup {
  display: none;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.7); /* Semi-transparent black color */
  width: 60%;
  max-width: 800px;
  border-radius: 15px;
  padding: 20px;
}

.video-popup-content {
  position: relative;
}

.video-popup video {
  width: 100%;
  border-radius: 10px;
}

.close-popup {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: transparent;
  color: #fff;
  border: none;
  cursor: pointer;
}

.overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black color */
  z-index: 9998;
}

JS

document.addEventListener("DOMContentLoaded", function() {
  const container = document.querySelector(".container");
  const cards = document.querySelectorAll(".card");
  const videoPopup = document.querySelector(".video-popup");
  const closePopup = document.querySelector(".close-popup");
  const popupVideo = document.querySelector(".video-popup video");
  const overlay = document.querySelector('.overlay');

  let totalWidth = 0;
  cards.forEach(card => {
    totalWidth += card.offsetWidth;
  });

  container.style.width = totalWidth + "px";

  container.addEventListener("mouseenter", function() {
    container.style.animationPlayState = "paused";
  });

  container.addEventListener("mouseleave", function() {
    container.style.animationPlayState = "running";
  });

  const reviewCards = document.querySelectorAll(".video-card");

  reviewCards.forEach(card => {
    card.addEventListener("click", function() {
      const videoSrc = card.querySelector("video source").getAttribute("src");
      popupVideo.setAttribute("src", videoSrc);
      videoPopup.style.display = "block";
      overlay.style.display = "block";
    });
  });

  closePopup.addEventListener("click", function() {
    popupVideo.pause();
    videoPopup.style.display = "none";
    overlay.style.display = "none";
  });
});

How to create tree structure from html element?

this is my element in my vue2 application:

<div class="child-elements-container draggable-container">
    <div>
        <div entity-type="entitytype1" type="elementType" id="2" class="single-element"></div>
        <div class="child-elements-container draggable-container">
            <div>
                <div entity-type="entitytype2" type="elementType" id="59" class="single-element"></div>
            </div>
        </div>
    </div>
    <div>
        <div entity-type="measures" type="elementType" id="3" class="single-element"></div>
        <div class="child-elements-container draggable-container">
            <div>
                <div entity-type="entitytype3" type="elementType" id="13" class="single-element"></div>
                <div class="child-elements-container draggable-container"></div>
            </div>
            <div>
                <div entity-type="entitytype2" type="elementType" id="14" class="single-element"></div>
                <div class="child-elements-container draggable-container"></div>
            </div>
        </div>
    </div>
    <div>
        <div entity-type="entitytype3" type="elementType" id="11" class="single-element">
        </div>
        <div class="child-elements-container draggable-container">
            <div>
                <div entity-type="entitytype3" type="elementType" id="12" class="single-element">
                </div>
                <div class="child-elements-container draggable-container"></div>
            </div>
        </div>
    </div>
</div>

I am trying to get a tree structure with it similar like this:

[
    {
        "id": "2",
        "children": [
            {
                "id": "59",
                "children": []
            }
        ]
    },
    {
        "id": "3",
        "children": []
    },
    {
        "id": "11",
        "children": [
            {
                "id": "12",
                "children": []
            }
        ]
    }
]

and I am using this function to get this hierarchy view:

const elementHierarchy = this.buildDraggedHierarchy(element);
                console.log(elementHierarchy);
buildDraggedHierarchy(el) {
            if (!el) {
                return [];
            }
            let children = [...el.querySelectorAll(":scope>div")];
            let output = children.map((child) => {
                return {
                    id: child.id,
                    type: child.getAttribute("type"),
                    children: this.buildDraggedHierarchy(child.querySelector(".draggable-container")),
                };
            });
        },

but output comes undefined. how can I fix it and get the array like how I showed? I think I am doing something wrong here: let children = […el.querySelectorAll(“:scope>div”)];
but I dont know how recursively I can fix this issue?

Remember data in previous session of the web page

I have a javascript enabled html page where a there are 3 text fields. When I reload the page, I would like the text fields retain the values I had earlier filled. Is this possible?

I have tried this way.

function Load() {
    document.getElementById("text").innerHTML = localStorage.getItem("name");
}
function Unload() {
    localStorage.setItem("name", document.getElementById("text").innerHTML);
}

Custom select with absolute position going behind the parent divs

I have a custom select which works well.

I also have a div, which opens and closes based on a state. Based on that state I change the height and overflow hidden to open and close the div.

When I use my select inside this div. It comes correctly when the dropdown comes below, but goes behind parent when the position is on top. (the select switches between top and bottom based on the remaining space in the screen).

I have added the images below.

I checked all the parent divs for any overflow or position issue, but couldn’t find any.

Dropdown below
Drop down on top

I have a div visibility problem.