How to programmatically run ESLint to prettify file?

After looking at the sparse docs for the ESLint Node.js API, I have this code:

const { ESLint } = require('eslint')
const ESLINT_CONFIG = require('../eslint.code.json')

async function lint(path) {
  // 1. Create an instance.
  const eslint = new ESLint({
    fix: true,
    overrideConfig: ESLINT_CONFIG,
    useEslintrc: false,
  })

  // 2. Lint files.
  const results = await eslint.lintFiles([path])

  // 3. Format the results.
  const formatter = await eslint.loadFormatter('stylish')
  const resultText = formatter.format(results)
  console.log(resultText)
}

lint('example.ts')

My project has a .eslintrc.json, but I want to override it completely (i.e. not use it), so I created a second one, eslint.code.json, which is minimal:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": ["./tsconfig.json"]
  },
  "parser": "@typescript-eslint/parser",
  "plugins": [
    "@typescript-eslint",
    "import",
    "simple-import-sort",
    "sort-exports",
    "typescript-sort-keys",
    "sort-keys",
    "prettier"
  ],
  "extends": ["prettier", "next"],
  "rules": {
    "curly": 2,
    "@typescript-eslint/quotes": [
      "error",
      "single",
      {
        "avoidEscape": true,
        "allowTemplateLiterals": true
      }
    ],
    "padding-line-between-statements": "off",
    "@typescript-eslint/padding-line-between-statements": [
      "error",
      { "blankLine": "always", "prev": "*", "next": "function" },
      { "blankLine": "always", "prev": "*", "next": "block" },
      { "blankLine": "always", "prev": "*", "next": "return" },
      { "blankLine": "always", "prev": "*", "next": "type" }
    ]
  }
}

My tsconfig.json is like this:

{
  "compilerOptions": {
    "target": "es5",
    "declaration": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react",
    "incremental": true,
    "outDir": "dist",
    "baseUrl": ".",
    "declarationMap": true
  },
  "exclude": ["node_modules", "dist"]
}

I am not sure I need to use my tsconfig at all, but there it is anyways.

So when I run it on an example file such as this:

function tanh(x) {
  return x.clamp(-15, 15).tanh()
}
function artanh(x: TorchTensor) {
  x = x.clamp(-1 + 1e-7, 1 - 1e-7)
  return torch
    .log(1 + x)
    .sub(torch.log(1 - x))
    .mul(0.5)
}

I would expect it to put a space between the two functions (because of the eslint config). Here is my package.json:

{
  "main": "src/index.js",
  "files": [
    "dist",
    "src"
  ],
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^5.48.1",
    "@typescript-eslint/parser": "^5.48.1",
    "eslint": "8.31.0",
    "eslint-config-next": "13.1.2",
    "eslint-config-prettier": "^8.6.0",
    "eslint-config-standard-with-typescript": "^27.0.1",
    "eslint-import-resolver-typescript": "^3.5.3",
    "eslint-plugin-import": "^2.27.4",
    "eslint-plugin-n": "^15.6.1",
    "eslint-plugin-prettier": "^4.2.1",
    "eslint-plugin-promise": "^6.1.1",
    "eslint-plugin-simple-import-sort": "^8.0.0",
    "eslint-plugin-sort-exports": "^0.8.0",
    "eslint-plugin-sort-keys": "^2.3.5",
    "eslint-plugin-typescript-sort-keys": "^2.1.0",
    "prettier": "^2.8.2"
  }
}

I am getting this error though:

node:internal/errors:491
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_INVALID_ARG_VALUE]: Failed to load plugin '@typescript-eslint' declared in 'CLIOptions': The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received ''
    at new NodeError (node:internal/errors:400:5)
    at createRequire (node:internal/modules/cjs/loader:1333:13)
    at Object.resolve (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2325:16)
    at ModuleResolver.resolve (/exampleproj/node_modules/@rushstack/eslint-patch/lib/modern-module-resolution.js:210:48)
    at ConfigArrayFactory._loadPlugin (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3392:33)
    at ConfigArrayFactory._loadPlugin (/exampleproj/node_modules/@rushstack/eslint-patch/lib/modern-module-resolution.js:219:43)
    at /exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3283:33
    at Array.reduce (<anonymous>)
    at ConfigArrayFactory._loadPlugins (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3279:22)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/exampleproj/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3079:44) {
  code: 'ERR_INVALID_ARG_VALUE'
}

What am I doing wrong? How can I simply format a string? Basically these are my related questions:

  • What am I doing wrong?
  • Am I setting the config correctly?
  • What is stylish, I couldn’t figure out what I need to set for that? (prettier?)

edit picture online using javascript or php

hello everyone im trying to find any script or any librarly or any framwork to edit picture like this link

https://mydoormaker.com/en/

what i want is sometime i can change image and return it to the user
like if i have doors type

door1 door2 door3

and when the user select the door i can change the color of the door or add door handle or add glass to the door im good with js and vuejs and php and laravel
and here is some example from what i want

https://doordesigner.solidor.co.uk/

my need is how i can edit images and return it to the user and marriage tow or theree images using php or js thanks

Changing background color of div based on pre-selected option in a php generated select menu

I have a php generated select option menu on my page with the options ‘Unverifed’, ‘Verified’ and ‘Banned’.

I am attempting to (automatically) change the background color of the statusField, based on which option is pre-selected (from database).

Corresponding Status options and background colors should be as follows:

Unverified – orange
Verified – green
Banned – red

For testing purposes, I am able to achieve the background color change (manually), by using ‘Select Option Menu Example #1’ (below), along with the ‘Change Background Color’ script below.

However… I will not be using Example #1 field on my site.

I will be using the php version, ‘Example #2’, so that I can populate the statusField’s pre-selected option with the particular status stored in the database.

Unfortunately… when I attempt to use the same ‘Change Background Color’ script with Example #2, the color does not automatically change.

Select Option Menu Example #1

<select id="status" name="status" class="statusField" value="<?php echo $_POST['status']; ?>">

<option value="Unverified" class="unverified">Unverified</option>
<option value="Verified" class="verified">Verified</option>
<option value="Banned" class="banned">Banned</option>

</select>

Select Option Menu Example #2

       <?php
            $selected = "$status";
            $options = array('Unverified', 'Verified', 'Banned');
            echo "<select id='status' name='status' class='statusField'>";
            foreach($options as $option){
                if($selected == $option) {
                    echo "<option selected='selected' value='$option'>$option</option>";
                }
                else {
                    echo "<option value='$option'>$option</option>";
                }
            }
            echo "</select>";
        ?>

Change Background Color – Script

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>

$(document).ready(function(){
$(document).on("change", ".statusField", function(){
var colors = ["orange", "green", "red"];
var wth = $(this).find(":selected").index();
var color = colors[ wth ];
$(".statusField").css("background-color", color );
});
});    

</script>

How to rewrite simple project in React

I have a simple project where you start at a register page which has validation checks. When you finally register you should have your session saved (not implemented yet, should be done with React locally I think) and go to another page where you can play tic tac toe.

I have the register page and the tic tac toe page. I’m pretty new to React. I’m just trying to practice by implementing it with React, but I can’t get it to work. And I’m still puzzled about the local session saving and I’m not quite sure how to do that either.

Code:

REGISTER PAGE:

index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <script type="text/javascript" src="script.js"></script>
        <link rel="stylesheet" type="text/css" href="styles.css">
        <title>Project</title>
    </head>
    <body>
        <div id="error" class="noerror"></div>
        
        <div class="container">
            <form onsubmit="return validate()" action="tictactoe.html" method="post" class="regform">
                <span class="registration">Registration</span>
                
                <input type="user" id="user" name="user" placeholder="Username">
                <input type="password" id="password" name="password" placeholder="Password">
                <input type="password" id="password2" name="password2" placeholder="Confirm password">
                
                <input type="submit" id="submit" value="Register">
            </form>
        </div>
    </body>
</html>

styles.css:

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 95vh;
}

.regform {
    display: flex;
    flex-flow: column wrap;
    width: 400px;
    padding: 20px;
    background-color: whitesmoke;
    border: 1px solid black;
}

.registration {
    background-color: yellowgreen;
    color: white;
    text-align: center;
    padding: 10px;
    margin: -21px -21px 10px -21px;
    text-transform: uppercase;
    font-weight: bold;
}

.error {
    word-wrap: normal;
    background-color: orangered;
    font-weight: bold;
    text-align: center;
    padding: 10px;
    margin-left: 5%;
    margin-right: 5%;
}

.noerror {
    display: hidden;
}

input {
    padding: 10px;
    margin: 10px 0px;
    border: 1px solid lightgrey;
}

input#submit {
    background-color: yellowgreen;
    color: white;
}

* {
    font-family: Arial, Helvetica, sans-serif;
}

script.js:

function validate() {
    var user = document.getElementById('user').value;
    var pass = document.getElementById('password').value;
    var pass2 = document.getElementById('password2').value;
    
    if(!/^[a-zA-Z0-9_]{3,16}$/.test(user)) {
        var msg = 'Username must be between 3 and 16 symbols. Can only contain lowercase and uppercase letters, one number and "_"!';
        showError(msg);
        return false;
    }
    
    if(!/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,256}$/.test(pass)) {
        var msg = 'Password must be between 8 and 256 symbols. Must contain atleast one lowercase and uppercase letter, one number and one symbol!';
        showError(msg);
        return false;
    }
    
    if(pass != pass2) {
        var msg = 'Passwords must match.';
        showError(msg);
        return false;
    }
}

function showError(msg) {
    document.getElementById('error').innerHTML = msg;
    document.getElementById('error').classList.add('error');
    document.getElementById('error').classList.remove('noerror');
}

TIC TAC TOE PAGE:

tictactoe_script.js:

var x = '10006';
var o = '9898';

var firstPlayerMove;
var gameWon;
var moves;

function showMsg(msg) {
    document.getElementById("msg").innerHTML = msg;
}

function setup() {
    firstPlayerMove = true;
    gameWon = false;
    moves = 0;
    showMsg("It's X's turn.");
}

function restart() {
    Array.prototype.forEach.call(document.getElementsByClassName("tile"), function(element) {
        element.innerHTML = "";
    });
    
    setup();
}

function makeMove(tile) {
    if(gameWon) {
        return false;
    }
    
    if(isValidMove(tile)) {
        moves++;
        
        if(firstPlayerMove) {
            tile.innerHTML = '&#' + x + ';';
        }
        else {
            tile.innerHTML = '&#' + o + ';';
        }
        
        if(checkWin()) {
            return true;
        }
        
        if(moves == 9) {
            showMsg("Draw.");
            return true;
        }
        
        firstPlayerMove = !firstPlayerMove;
        
        if(firstPlayerMove) {
            showMsg("It's X's turn.");
        }
        else {
            showMsg("It's O's turn.");
        }
    }
}

function isValidMove(tile) {
    return tile.innerHTML === '';
}

function checkWin() {
    var tiles = document.getElementsByClassName("tile");
    var xTiles = new Array(9);
    var oTiles = new Array(9);
    
    for(var i = 0; i < tiles.length; i++) {
        if(tiles[i].innerHTML === String.fromCharCode(x)) {
            xTiles[i] = 1;
        }
        
        if(tiles[i].innerHTML === String.fromCharCode(o)) {
            oTiles[i] = 1;
        }
    }
    
    if(hasWinningPattern(xTiles)) {
        showMsg("Player 1 (X) won.");
        return true;
    }
    
    if(hasWinningPattern(oTiles)) {
        showMsg("Player 2 (O) won.");
        return true;
    }
    
    return false;
}

function hasWinningPattern(tiles) {
    var winningPatterns = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];
    
    for(var i = 0; i < winningPatterns.length; i++) {
        var pattern = winningPatterns[i];
        
        var win = true;
        for(var j = 0; j < pattern.length; j++) {
            if(tiles[pattern[j]] != 1) {
                win = false;
            }
        }
        
        if(win) {
            gameWon = true;
            return true;
        }
    }
    
    return false;
}

tictactoe_styles.css:

.board, .start, .msg {
    position: absolute;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

.board {
        margin-top: 110px;
    width: 600px;
    height: 600px;
    border: 1px solid lightgrey;
    font-size: 0px;
    max-width: 100%;
    max-height: 100%;
}
 
.row {
    width: 600px;
    height: 200px;
    font-size: 0px;
}
 
.tile {
    border: 1px solid lightgrey;
    width: 198px;
    height: 200px;
    display: inline-block;
    font-size: 150px;
    text-align: center;
    vertical-align: middle;
    line-height: 200px;
}

.tile:hover {
    background-color: grey;
}

.start {
    width: 100px;
    height: 50px;
    margin-top: 50px;
}

.msg {
    width: 300px;
    height: 50px;
    margin-top: 10px;
    font-size: 32px;
    font-weight: bold;
    text-align: center;
    font-family: Arial, Helvetica, sans-serif;
}

tictactoe.html:

<html>
    <head>
        <meta charset="UTF-8" />
        <title>Project</title>
        <link rel="stylesheet" type="text/css" href="tictactoe_styles.css">
        <script src="tictactoe_script.js"></script>
    </head>
    <body onload="setup()">
        <button onclick="restart()" class="start">Restart</button>
        <div class="board">
            <div class="row">
                <div onclick="makeMove(this)" class="tile"></div>
                <div onclick="makeMove(this)" class="tile"></div>
                <div onclick="makeMove(this)" class="tile"></div>
            </div>
            <div class="row">
                <div onclick="makeMove(this)" class="tile"></div>
                <div onclick="makeMove(this)" class="tile"></div>
                <div onclick="makeMove(this)" class="tile"></div>
            </div>
            <div class="row">
                <div onclick="makeMove(this)" class="tile"></div>
                <div onclick="makeMove(this)" class="tile"></div>
                <div onclick="makeMove(this)" class="tile"></div>
            </div>
        </div>
        <div class="msg" id="msg"></div>
    </body>
</html>

This is all of the code and it works fine. Here is how I tried to implement the register page on react but failed:

index.js:

//import React, { Fragment } from 'react';
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
//import App from './App';
import reportWebVitals from './reportWebVitals';

import { useState } from 'react';

function Register() {
  const[msg, setMessage] = useState('');
  const [user, setUser] = useState('');
  const [pass, setPass] = useState('');
  const [pass2, setPass2] = useState('');

  function validate() {
    if(!/^[a-zA-Z0-9_]{3,16}$/.test(user)) {
      setMessage('Username must be between 3 and 16 symbols. Can only contain lowercase and uppercase letters, one number and "_"!');
    }
    
    if(!/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,256}$/.test(pass)) {
      setMessage('Password must be between 8 and 256 symbols. Must contain atleast one lowercase and uppercase letter, one number and one symbol!');
    }
    
    if(pass !== pass2) {
      setMessage('Passwords must match.');
    }
  }
  
  return (<>
    <div class="container">
      <div id="error" class="error">{msg}</div>
            
                <span class="registration">Registration</span>
                
                <input onchange={()=>setUser} type="user" id="user" name="user" placeholder="Username"/>
                <input onchange={()=>setPass} type="password" id="password" name="password" placeholder="Password"/>
                <input onchange={()=>setPass2} type="password" id="password2" name="password2" placeholder="Repeat Password"/>
                
                <input onchange={()=>validate()} type="button" id="submit" value="Register"/>
            
        </div>
  </>)
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Register/>
);

If someone could help me implement the code in React that would be great! Any help is greatly appreciated! Thanks in advance!

How do you know if your website page is scrolled to the top

I am using javascript and would like to have a menu in my website page when the page is scrolled to the top the menu background becomes transparent and when you scroll down the menu background changes and remains at the top of the page. I just can’t find how you can know in javascript if your page is at the top. thanks

/

How to get the text of dragged item in javascript

I am learning about drag and drop and I created this simple script (Run script) to check

function onDrag(ev) {
  console.log('You are dragging', ev.target.className)
}

function onDrop(ev) {
  ev.preventDefault();
  var ul =  ev.target;
  var li = document.createElement('li');
  li.appendChild(document.createTextNode("Text?"));
  ul.parentElement.appendChild(li);

}

function onOverDrop(ev) {
  ev.preventDefault();
}
ul, li{border:1px solid green}

.container-left, .container-right {width:45%; margin-left:1%; float:left}
<div class="container-left">
  <ul>
    <li class="A" 
        draggable="true" 
        ondragstart="onDrag(event)">A</li>
    
    <li class="B"  
        draggable="true" 
        ondragstart="onDrag(event)">B</li>
    
    <li  class="C"  
        draggable="true"
        ondragstart="onDrag(event)">C</li>
    
    <li class="D" 
        draggable="true"
        ondragstart="onDrag(event)">D</li>
  </ul>
</div>


<div class="container-right">
  <ul>
    <li> 1
      <ul ondrop="onDrop(event)" ondragover="onOverDrop(event)">
        <li class="1"></li>
      </ul>
    </li>
    <li> 2
      <ul ondrop="onDrop(event)" ondragover="onOverDrop(event)">
        <li class="2"></li>
      </ul>
    </li>
    <li> 3
      <ul ondrop="onDrop(event)" ondragover="onOverDrop(event)"> 
        <li class="3"></li>
      </ul>
    </li>
    <li> 4
      <ul ondrop="onDrop(event)" ondragover="onOverDrop(event)"> 
        <li class="4"></li>
      </ul>
    </li>
  </ul>
</div>

The issue I have is that inside onDrop method I would like the text and class of the item I am dragging. For example when I drag A into the right side and drop it, instead of getting Text? I want to get A

How to configure prettier or eslint to put a newline after function definitions and other blocks?

Right now prettier is giving me this:

function _project(x, k, dim: number = -1, eps: Float = -1.0) {
  if (eps < 0) {
    if (x.dtype == torch.float32) {
      eps = 4e-3
    } else {
      eps = 1e-5
    }
  }
  maxnorm = (1 - eps) / sabs(k) ** 0.5
  maxnorm = torch.where(k.lt(0), maxnorm, k.newFull([], 1e15))
  norm = x.norm({ dim: dim, keepdim: true, p: 2 }).clampMin(1e-15)
  cond = norm > maxnorm
  projected = (x / norm) * maxnorm
  return torch.where(cond, projected, x)
}
function lambdaX(
  x: TorchTensor,
  k: TorchTensor,
  keepdim = false,
  dim = -1,
) {
  return _lambdaX(x, k, { keepdim: keepdim, dim: dim })
}
function _lambdaX(
  x: TorchTensor,
  k: TorchTensor,
  keepdim: Bool = false,
  dim: number = -1,
) {
  return (
    2 /
    (1 + k * x.pow(2).sum({ dim: dim, keepdim: keepdim })).clampMin(
      1e-15,
    )
  )
}
function inner(
  x: TorchTensor,
  u: TorchTensor,
  v: TorchTensor,
  k,
  keepdim = false,
  dim = -1,
) {

Is there a way to configure either prettier or eslint to put a space after some of the blocks, so it is more like this:

function _project(x, k, dim: number = -1, eps: Float = -1.0) {
  if (eps < 0) {
    if (x.dtype == torch.float32) {
      eps = 4e-3
    } else {
      eps = 1e-5
    }
  }
  
  maxnorm = (1 - eps) / sabs(k) ** 0.5
  maxnorm = torch.where(k.lt(0), maxnorm, k.newFull([], 1e15))
  norm = x.norm({ dim: dim, keepdim: true, p: 2 }).clampMin(1e-15)
  cond = norm > maxnorm
  projected = (x / norm) * maxnorm

  return torch.where(cond, projected, x)
}

function lambdaX(
  x: TorchTensor,
  k: TorchTensor,
  keepdim = false,
  dim = -1,
) {
  return _lambdaX(x, k, { keepdim: keepdim, dim: dim })
}

function _lambdaX(
  x: TorchTensor,
  k: TorchTensor,
  keepdim: Bool = false,
  dim: number = -1,
) {
  return (
    2 /
    (1 + k * x.pow(2).sum({ dim: dim, keepdim: keepdim })).clampMin(
      1e-15,
    )
  )
}

function inner(
  x: TorchTensor,
  u: TorchTensor,
  v: TorchTensor,
  k,
  keepdim = false,
  dim = -1,
) {

My prettier config currently is:

{
  semi: false,
  parser: 'typescript',
  trailingComma: 'all',
  singleQuote: true,
  printWidth: 72,
  tabWidth: 2,
  useTabs: false,
  arrowParens: 'avoid',
  quoteProps: 'as-needed',
  bracketSpacing: true,
  proseWrap: 'always',
  endOfLine: 'lf',
  singleAttributePerLine: true,
  importOrder: [
    '^\w(.*)$',
    '^@(.*)$',
    '~(.*)$',
    '\..(.*)$',
    '\.(.*)$',
  ],
  importOrderSeparation: true,
  importOrderSortSpecifiers: true,
}

And I am programmatically running it like this:

const prettier = require('prettier')

function pretty(string) {
  return prettier.format(string, config)
}

What is as close as you can get to this “space between blocks” style?

Could someone give me an explanation of how to make these types of custom alerts into inputs?

Could someone give me an explanation of how to make these types of custom alerts into inputs?

Print

Code of the input error:

<div class="andes-form-control__bottom"><svg class="andes-form-control__error-icon" width="12" height="12" viewBox="0 0 12 12"><defs><rect id="a" width="12" height="12" rx="6"></rect></defs><g fill="none" fill-rule="evenodd"><mask id="b" fill="#fff"><use xlink:href="#a"></use></mask><g mask="url(#b)"><path fill="#F23D4F" d="M-.686-.343h13.371v12.686H-.685z"></path><path fill="#FFF" fill-rule="nonzero" d="M6 7.636a.727.727 0 1 1 0 1.455.727.727 0 0 1 0-1.455zm.727-4.727l-.182 4h-1.09l-.182-4h1.454z"></path></g></g></svg><span id="user_id-message" class="andes-form-control__message"><div class="input-error"><div class="ui-form__message">Revise o seu e-mail ou usuário.</div></div></span></div>

How to click on a year in calendar with selenium using javaScript

I am trying to write Selenium test with javaScript but was unable to fill calendar data. It is using a dropdown menu

let calendar = driver.findElement(By.xpath(“//input[@id=’dateOfBirthInput’]”))
await calendar.click()
let month = driver.findElement(By.xpath(“//select[@class=’react-datepicker__month-select’]”))
await month.click()
await month.sendKeys(Key.DOWN, Key.DOWN, Key.RETURN)

let year = driver.findElement(By.xpath(“//select[contains(@class,’react-datepicker__year-select’)]”)).value = “1988”

How can i clcik on value that i need. Consol loging year gives me 1988 but idk how to select it in browser. Is there any other way besides pressing Key.DOWN 35 times. I cannot use Select class in js…

Scaling text to fit within Textbox when changing text value programmatically

I am using a Textbox in my canvas application to allow users to edit text. This is working fantastically for me, as I want text to wrap during editing, and wrap/unwrap as the width of the box is shrunken and expanded.

However, I have a secondary use case that I need some guidance on.

Occasionally, I need to replace the text in the textbox programmatically. In this scenario, I do not want the textbox to wrap text or expand when the text is too long for the width. Instead, I would like to reduce the fontSize so that the text fits on one line.

Note: I only do this text replacement once when the canvas is loaded (or just before in the JSON).

I currently handle this with IText using the following code, but I cannot seem to modify it in a way that works reliably with Textbox. I also lose out on the fantastic text wrapping if I use IText, which is why I’m evaluating this.

const handleTextChanged = ({ target }: { target: fabric.Object }) => {
  const { fixedWidth, width, fontSize } = target

  if (width > fixedWidth) {
    // Shrink the font size to stay within the max width
    target.fontSize = Math.round((fontSize * fixedWidth) / (width + 1))
  }

  target.width = fixedWidth
}

Is there a way to achieve something like this using just Textbox? That is, I would like to keep text wrapping and unwrapping functionality during normal editing, but I would also like to load text in programmatically and have the font size scale to fit the box when I load the canvas.

How can i delete this collection in firebase?

i recently began to use firebase and i ran into a problem, to get it straight, i want to make a e-commerce site, ofcourse it has cart, i used firebase for my back-end, for every user, i create a document in “users” collection, each user’s document id is the uid of that given user. On every document, i have a cart, and in the cart, the products, on my cart page, i want to have a “Empty Cart” that deletes all the products, meaning it deletes “cart” collection. How can i do that? I have left some photos below that will probably explain the problem better.

Image of the firebase tree

I tried this and it did not work!

const deleteCart = async () => {
    const cartDoc = `users/${user.uid}/cart`
    
    await deleteDoc(db, cartDoc)
    
    }

i get this error : ” TypeError: Cannot use ‘in’ operator to search for ‘_delegate’ in undefined “

Alternative languages for web development that offer the benefits of strong typing and efficient refactoring? [closed]

What are the available options for web development that allow for the use of a strongly typed language, while addressing the scalability, testing, and refactoring challenges that are commonly associated with using JavaScript?

Are there any languages or frameworks that provide a balance of the benefits offered by strongly typed languages, such as Java, and the flexibility and ease of use of JavaScript-like programming?

Additionally, are there any alternatives to TypeScript that still offer the benefits of strong typing without the limitations of JavaScript?

Sub-menu moving moving when using sticky

I create a submenu for a nav bar using HTML and CSS. I want the position of the submenu to be fixed since I want the sub-menu to open at the same spot despite which element of the nav bar is hovered on. Further, I’m using sticky to fix the position of the navbar. The problem is when I scroll down if the sub-menu is open, it’s moving down. I’m not sure what is causing this

/*for Sticky*/

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky+.sub-menu {
  padding-top: 0px;
}


/*style for nav bar*/

nav {
  display: inline-flex;
  width: 100%;
}

.nav-list {
  display: flex;
  width: 100%;
  margin-top: .7rem;
  padding-left: 1.1rem;
}

.nav-list li {
  position: relative;
}

.nav-list>li>a {
  color: black;
  display: block;
  font-size: 1rem;
  padding: 1.3rem 1rem;
  text-transform: uppercase;
}

.sub-menu {
  display: flex;
  position: fixed;
  box-sizing: border-box;
  background-color: black;
  visibility: hidden;
  top: 4.5rem;
  /*adjust postion */
  left: -3rem;
  width: 82.5rem;
  height: 35rem;
}

.sub-menu a {
  position: relative;
  top: 2rem;
  color: white;
  font-size: 1.1rem;
  font-weight: 200;
  padding: 3rem 40px 0 40px;
}

.sub-menu a:hover {
  color: #7e7978;
}

.nav-list li:hover>.sub-menu {
  visibility: visible;
}
<div class="main" id="navbar">
  <div class="logo">
    <a href="">XZY</br> NAME</a>
  </div>
  <nav>
    <ul class="nav-list">
      <li>
        <a href="">Category</a>
        <ul class="sub-menu">
          <li><a href="#">shirts</a> </li>
        </ul>
      </li>
      <ul>
  </nav>
</div>


<div class="content for scroll">
  <a>Enim sociosqu class viverra pellentesque consectetuer a hymenaeos lectus lacinia potenti suscipit sagittis velit. Primis habitant sociis. Mauris nonummy Donec, habitasse vitae ullamcorper aptent velit ligula. Natoque placerat class nunc, natoque iaculis non ac iaculis. Turpis nullam. Suscipit curae; nisl mi eleifend venenatis est phasellus luctus sociosqu facilisis egestas. Porta suspendisse inceptos sociis placerat adipiscing auctor aliquam vel libero aptent. Duis class, sollicitudin, massa sodales, netus volutpat nibh lobortis bibendum est torquent ipsum volutpat pharetra ac eleifend consequat magna vitae tincidunt euismod eleifend lobortis dapibus vitae. Cras sollicitudin nullam per inceptos elementum dolor varius rutrum sollicitudin augue vestibulum ullamcorper donec pharetra feugiat aliquet etiam est turpis velit eros, eu arcu. Elementum interdum tincidunt. Dolor semper consectetuer morbi vivamus aliquam. Id class platea pharetra nec varius tristique dis metus. Fusce nascetur sociosqu ultricies leo mauris maecenas vulputate. Metus vulputate purus cum habitant, erat semper bibendum. Nisi per aliquam nec tellus turpis Curae;. Praesent ornare curae; vehicula mattis potenti vitae torquent montes lorem nam gravida eget sapien natoque risus per nulla quisque ornare ultrices erat morbi dignissim scelerisque dictumst porttitor leo. Aptent facilisis pharetra cras curae; aenean.

Tellus cursus auctor. Volutpat commodo id. Tempor nec natoque integer leo senectus suscipit. Aliquam quisque nulla litora vivamus hymenaeos praesent dui primis. Mollis praesent lobortis tincidunt parturient venenatis. Mattis. Lectus fermentum ornare ornare senectus interdum hac rhoncus sociis litora. Non in lacus egestas sociis. Consequat justo posuere dapibus ornare nulla sollicitudin nascetur donec hymenaeos. Pharetra aliquet imperdiet molestie nullam libero habitant ipsum pharetra quisque ad class natoque hymenaeos justo quisque. Class. Risus duis lacinia eleifend magna penatibus urna, posuere cras Massa quam est mi sapien nisl placerat. Libero fermentum pharetra taciti, auctor metus eleifend mus fermentum luctus felis. Odio condimentum. Pellentesque senectus hymenaeos eget nostra ac vitae. Aenean fusce faucibus dictum. Ornare natoque. Sem. Lobortis malesuada. Lacus ante donec turpis venenatis volutpat, amet condimentum urna pulvinar arcu vitae maecenas libero iaculis elementum senectus dapibus vulputate feugiat viverra pulvinar mattis purus hac rhoncus ridiculus egestas a senectus. Sollicitudin.

Enim, dictumst nullam platea molestie nonummy. Non, donec montes. Erat id. Eu erat commodo ornare potenti curabitur pharetra et curae; velit nec ullamcorper morbi nonummy hymenaeos, montes montes parturient fermentum per. Quis auctor nascetur class eu Venenatis. Pellentesque euismod cras imperdiet malesuada neque scelerisque mollis. Nec molestie pulvinar quis eget erat. Sapien vestibulum nullam metus nec placerat nisl ridiculus sociis suscipit consequat sed facilisis arcu senectus molestie facilisi interdum at vehicula tempor penatibus malesuada. Consectetuer eu adipiscing non. Curae; integer varius pede mi mus. Metus malesuada congue elit molestie orci urna sed ornare vel curabitur vulputate congue convallis felis maecenas adipiscing ac fermentum. Mus fringilla lacus. Non tortor rutrum dis habitasse mattis elementum eleifend. Arcu. Nascetur. Porttitor per, non porttitor. Potenti mi mi sapien nibh. Malesuada praesent per orci eu pulvinar dui ante mollis. Elit luctus sagittis tempus augue cras nunc interdum scelerisque sapien nec dapibus conubia est euismod aliquam arcu ligula porta metus curabitur eleifend sed. Ad sagittis ad. Nullam blandit maecenas dolor orci Quam pharetra duis. </a>
</div>

<script>
  window.onscroll = function() {
    myFunction()
  };

  var navbar = document.getElementById("navbar");
  var sticky = navbar.offsetTop;

  function myFunction() {
    if (window.pageYOffset >= sticky) {
      navbar.classList.add("sticky")
    } else {
      navbar.classList.remove("sticky");
    }
  }
</script>

Click on next element in javascript

I have multiple same containers and each one contains same anchors like:

<div>
  <a href="#" class="button1">Button 1a</a>
  <a href="#" class="button2">Button 2a</a>
<div>
<div>
  <a href="#" class="button1">Button 1b</a>
  <a href="#" class="button2">Button 2b</a>
<div>
<div>
  <a href="#" class="button1">Button 1c</a>
  <a href="#" class="button2">Button 2c</a>
<div>

What I try to achieve is when I click on .button1 should start trigger and auto click on closest .button2

My js code now looks like:

const btn = document.querySelectorAll('.button1')

btn.forEach(function(btn) {
    btn.addEventListener("click", function() {
         console.log(this.innerText)
       this.closest('.button2').click()
    });
});

And here is fiddle: https://jsfiddle.net/4nhvtao1/4/