Why is this JS module imported with a “default” property in TypeScript?

This code from a custom i18n module, located in ./esm/locale/en.js:

import cardinal from '../rules/rule5';
import ordinal from '../rules/rule42';
var pluralRule = {
  ordinal: ordinal,
  cardinal: cardinal,
};
export default pluralRule;

Is exported in package.json with

{
  "exports": {
    "./en": {
       "default": "./esm/locale/en.js",
    }
  }
}

The i18n module is installed as dependency in a project, and used as

// some .ts file in the project
import en from 'custom-i18n/en';

console.log(en);
// { default: [Getter] }

Why is en having { default } instead of { ordinal, cardinal }?

Click button once to have text appear and fade instead of clicking twice? (html, css, javascript)

As this code is now, I must press twice to have the text appear and fade.

How can I press the button only once to have the “Added!” text appear and fade? I would like this to happen for every time I click the button.

I have tried focus with CSS. I have also tried rearranging javascript code, as well as inserting a while loop in the javascript, but I must be doing something wrong.

Thanks

  function cartAdded() {
    var text = document.getElementById("added-notification");
    if (text.style.display === "none") {
      text.style.display = "block";
    } else {
      text.style.display = "none";
    }
  }
  .added-fade-out {
    opacity: 0;
    display: none;
    animation: fadeOut 1s ease-out;

  }

  @keyframes fadeOut {
    0% {
      opacity: 1;
      display: none;
    }

    50% {
      opacity: 0.5;
      display: block;
    }

    100% {
      opacity: 0;
      display: none;
    }
  }
  <button type='button' onclick="cartAdded()">Click me</button>
  <p id='added-notification' class="added-fade-out">Added!</p>

How to detect if user navigate back (mobile) in Javascript?

I have a simple HTML file that has a javascript code:

<p>Press The Back Button and see a message!</p>

<script>
window.onpopstate = function(event) {
    alert("location: " + document.location);
}
</script>

I’m using Android 11 with the latest version of Google Chrome, when I press the back button, I want to show an alert with the location.

enter image description here

How I can do this? Why my code is not working?

Thymeleaf th:each – How to disable generating the div tags

                <div class="question" th:each="question : ${questions}">
                    <h2 id="question" class="description" th:text="${question.description}">Question goes here</h2>
                    <div id="answer-buttons">
                        <button class="btn"><div class="answer" th:text="${question.possibleAnswers.get(0).content}" th:classappend="${question.correctAnswer == 1 ? 'correct-answer' : ''}">Answer 1</div></button>
                        <button class="btn"><div class="answer" th:text="${question.possibleAnswers.get(1).content}" th:classappend="${question.correctAnswer == 2 ? 'correct-answer' : ''}">Answer 2</div></button>
                        <button class="btn"><div class="answer" th:text="${question.possibleAnswers.get(2).content}" th:classappend="${question.correctAnswer == 3 ? 'correct-answer' : ''}">Answer 3</div></button>
                        <button class="btn"><div class="answer" th:text="${question.possibleAnswers.get(3).content}" th:classappend="${question.correctAnswer == 4 ? 'correct-answer' : ''}">Answer 4</div></button>
                    </div>
                    <button id="next-btn">Next</button>
                </div>

If I figured correctly, th:each from the above code makes a new division for every question in questions, similar to this:

            <div class="quiz">
                <div class="question">
                    <h2 id="question" class="description">Question</h2>
                    <div id="answer-buttons">
                        <button class="btn"><div class="answer">Answer 1</div></button>
                        <button class="btn"><div class="answer correct-answer">Answer 2</div></button>
                        <button class="btn"><div class="answer">Answer 3</div></button>
                        <button class="btn"><div class="answer">Answer 4</div></button>
                    </div>
                    <button id="next-btn">Next</button>
                </div>
            </div>

Questions come from database and I have js file to handle them but in order to do so I don’t want extra html bodies to be created.

So my question is, does Thymeleaf have some disabler mechanism for above mentioned problem or do I need to change the structure of my code?

For any use, here is how my script handles the data:

const questionsFromDb = document.querySelectorAll('.question');

// Template
const questions = [
    {
        question: "Which is the largest animal on the planet?",
        answers: [
            {text: "Shark", correct: false},
            {text: "Blue whale", correct: true},
            {text: "Elephant", correct: false},
            {text: "Giraffe", correct: false}
        ]
    },
    {
        question: "Which is the smallest country on the planet?",
        answers: [
            {text: "Vatican City", correct: true},
            {text: "Bhutan", correct: false},
            {text: "Nepal", correct: false},
            {text: "Shri Lanka", correct: false}
        ]
    },
    {
        question: "Which is the largest desert on the planet?",
        answers: [
            {text: "Kalahari", correct: false},
            {text: "Gobi", correct: false},
            {text: "Sahara", correct: false},
            {text: "Antarctica", correct: true}
        ]
    },
    {
        question: "Which is the smallest continent on the planet?",
        answers: [
            {text: "Asia", correct: false},
            {text: "Australia", correct: true},
            {text: "Arctic", correct: false},
            {text: "Africa", correct: false}
        ]
    }
];

// Parsing Data
questionsFromDb.forEach(questionFromDb => {
    const questionDescription = questionFromDb.querySelector('.description').innerText;
    const answerElements = questionFromDb.querySelectorAll('.answer');

    const answers = [];

    answerElements.forEach((answerElement, index) => {
        const answerText = answerElement.innerText;
        const isCorrect = answerElement.classList.contains('correct-answer');

        answers.push({ text: answerText, correct: isCorrect });
    });

    questions.push({
        question: questionDescription,
        answers: answers
    });
});

// ... Non-relative code below

Income satisfaction increases

How can I increase my income?

Am hard working, but I want make more than I work, so am looking for a way to double up. Making profits from another source will help and make a lot of things happen faster and better especially for the people in the area

Route at location “/” does not have an element. This means it will render an with a null value by default resulting in an “empty” page

It should navigate to “http://localhost:3001/auth/sign-in” route, whenever “/auth/sign-in” or “/auth/sign-in” routes are not matched. Is there any way to solve this problem?

<BrowserRouter>
      <Routes>
        <Route path="/">
          <Route path="auth" element={<AuthContainer />}>
            <Route
              path="sign-in"
              element={<SignInForm onLoadUser={loadUser} />}
            />
            <Route
              path="sign-up"
              element={<SignUpForm onLoadUser={loadUser} />}
            />
          </Route>
        </Route>
        <Route path="*" element={<Navigate to="/auth/sign-in" replace />} />
      </Routes>
</BrowserRouter>

Convert array of object arrays to a single array in JavaScript

I have an array of objects having multiple arrays

 const arr =  [
    {
        JUNE: [
            {
                "iD": "67854",
                "event": " closed",
                "title": "test",
                "startDate": "2024-06-20",
                "endDate": "2024-07-25"
            }
        ]
    },
    {
        MAY: [
            {
                "ID": "908765",
                "event": "closed",
                "title": "test",
                "startDate": "2024-05-21",
                "endDate": "2024-06-27"
            },
            {
                ID: "12345",
                event: "open",
                title: "test123",
                startDate: "2024-05-21",
                endDate: "2024-06-27"
            }
        ]
    }
]

Output I need

   [
    {
        ID: "67854",
        event: "closed",
        title: "test",
        startDate: "2024-06-20",
        endDate: "2024-07-25"
    },
    {
        ID: "908765",
        event: "closed",
        title: "test",
        startDate: "2024-05-21",
        endDate: "2024-06-27"
    },
    {
        ID: "12345",
        event: "open",
        title: "test123",
        startDate: "2024-05-21",
        endDate: "2024-06-27"
    }

]

Typescript dynamic type literals

I recently stumbled upon interesting problem. I’m trying to create a vuejs wizard component which accepts configuration objects. Demo type looks like this:

type WizardConfiguration = {
  steps: {
      name: string,
      fields: {
        fieldName: string;
      }[]
    watchers: (ARGUMENTS) => void
    }[]
}

The problems stands in the watchers line. I want watchers callback to accept array of field names which were specified in the fields array. Example would look like this:

const config: WizardConfiguration = {
  steps: {
    name: "Step 1",
    fields: [
      { fieldName: "Field 1" }
    ],
  watchers: ([HERE I GET A INTELLISENSE of "Field 1"]) => {
    // do smth
  }
  }

Is something like this event possible in the current state of ts?

Thanks

Is it possible to cache uploaded image in browser?

I have an image-editor app, where I’m uploading an image and being redirected to another URL and downloading same image from server. Can I cache somewhere an image to skip the part, where I’m downloading an image, which I just uploaded? Saving a blob to localStorage is too tricky, because of few issues (size limit, string values only).

How to avoid “Typed Svelte Components” on svelte, using Typescript

In a simple, very simple svelte (Not Svelte Kit), using Typescript, VSCode is giving me this error in “Router” and “Route” classes of svelte-routing:

CODE:

<script lang="ts">
import {
    Router,
    Route,
    Link
} from 'svelte-routing';

const url = "";
</script>

<Router on:route> // ERROR HERE
    <Route path=""> // ERROR HERE
        <span>"other"</span>
    </Route>
</Router>

ERROR:

Argument of type ‘typeof Router’ is not assignable to parameter of
type ‘ConstructorOfATypedSvelteComponent’. Type ‘typeof Router’
provides no match for the signature ‘new (args: { target: any; props?:
any; }): ATypedSvelteComponent’.

Possible causes:

You use the instance type of a component where you should use the constructor type Type >definitions are missing for this Svelte Component.

If you are using Svelte 3.31+, >use SvelteComponentTyped to add a definition:
import type { SvelteComponentTyped } from “svelte”;
class ComponentName extends SvelteComponentTyped<{propertyName: string;}> {}ts(2345)

This works for me using Native JS but not with typescript.

I do not know if there is a incompatibility with Svelte and Typescript, Svelte-Routing module and typescript, or I’m doing something wrong.

Thanks everyone.

problem with error module vercel/turbopack

Hello my problem is this error.
`./node_modules/next/dist/client/components/react-dev-overlay/internal/helpers/use-websocket.js:86:8
Module not found: Can’t resolve ‘@vercel/turbopack-ecmascript-runtime/dev/client/hmr-client.ts’

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js
./node_modules/next/dist/client/components/app-router.js
./node_modules/next/dist/client/app-call-server.js
./node_modules/next/dist/build/webpack/loaders/next-flight-loader/action-client-wrapper.js
./src/actions/register.ts
./components/auth/register-form.tsx
./src/pages/auth/register/index.tsx`

I can try create auth. I think problem we find in register.ts or db.ts. i dont know.
this is my github repository with code. https://github.com/ThomasTomanec/portfolio-website

I try turbopack when i add to package.json in start:next dev –trubo.
my error is solved but appered a new error, bcs turbo vercel working only with browser client and prisma database need server client.

passport signUp successRedirect doesn`t work

Im trying to write signUp proccess with passport.js local-strategy and it works and save user data in dataBase but it redirects me to my user data object instead of what i specified in successRedirect.

This is my passport local-strategy file:

passport.serializeUser((user, done)=>{
    done(null , user.id);
})

passport.deserializeUser((id, done)=>{
    User.findById(id).then((err,user)=>{
        done(err,user);
    })
})

passport.use("local" , new Strategy({
    usernameField : 'mobileNumber',
    passwordField : 'password',
    passReqToCallback : true
} , (req, mobileNumber, password, done)=>{
    User.findOne({'mobileNumber' : mobileNumber})
    .then((user, err)=>{
        if(err) return done(err)
        if(user) return done(null , false , req.flash('errors' , 'This number is already use'));
        const addUser = new User({
            name : req.body.name,
            lastName: req.body.lastName,
            mobileNumber,
            password
        })

        addUser.save().then(err => {
            if(err) return done(err , false , req.flash('errors' , 'Something wrong try again later!'));
            return done(null , user);
        })
    })
}))

And this is my signUpController:

class SignUpController extends controller {
  showForm(req, res) {
    res.render("SignUp", { messages: req.flash("errors") });
  }
  async postForm(req, res, next) {
    const result = await this.validationForm(req, res);
    if (result) {
      this.register(req, res, next);
    } else res.redirect("/register");
  }
  register(req, res, next) {
    passport.authenticate("local", {
      successRedirect: "/",
      failureRedirect: "/register",
      failureFlash: true,
    })(req, res, next);
  }
}

export default new SignUpController();

My route file:

import express from 'express';
import HomeController from '../controllers/homeController.js';
import SignUpController from '../controllers/signUpController.js';
import RegisterValidator from '../validators/registerValidator.js';

const router = express.Router();

router.get("/", HomeController.index)
router.get("/register", SignUpController.showForm)
router.post("/register", RegisterValidator.handler(), SignUpController.postForm)

export default router;

Appending a random number to an appended text input fields

Please note in input2 that the RanNum is entirely replacing the input value. I would like to append it. Where am I going wrong?

If the input1 is “hey hey”, I want the output in the other 3 fields to be:

[email protected] (7 being a RanNum)
[email protected]
[email protected]

var min = 1;
var max = 9;
var RanNum = Math.floor(Math.random() * (max - min + 1)) + min;
  
var input1 = document.getElementById('first_name');
var input2 = document.getElementById('email');
var input3 = document.getElementById('username');
var input4 = document.getElementById('location');

input1.addEventListener('change', function() {
  input2.value = input1.value.replace(/s+/g,'').trim().value=RanNum + "@gmail.com";
  //input2.value = input1.value.replace(/s+/g,'').trim() + .value=RanNum + "@gmail.com";
  input3.value = input1.value.replace(/s+/g,'').trim() + "@gmail.com";
  input4.value = input1.value.replace(/s+/g,'').trim() + "@gmail.com";
});
<input type="text" id="first_name" />
<input type="text" id="email" />
<input type="text" id="username" />
<input type="text" id="location" />

How to set up a custom js variable?

GTM has a datalayer variable, how do I write code for a custom js variable that will work similarly to datalayer variable? For example, I have a datalayer variable that returns the value of the EventCategory parameter from datalayer, how can I return the same value in a custom js?
It is important that the custom js variable should not contain references to other variables from GTM

This code is not working correctly

function getLastEventCategory() {
  // Access the dataLayer directly, using "var" instead of "const"
  var dataLayer = window.dataLayer || [];

  // Find the last event with an "eventCategory" parameter
  var lastEventCategory = dataLayer.slice().reverse().find(function(event) {
    return event.eventCategory;
  });

  // Return the "eventCategory" value or an empty string if not found
  return lastEventCategory ? lastEventCategory.eventCategory : '';
}

Having a very basic probem with PIXI.js, unable to render a sprite on the screen

Apparently I am overlooking something very basic about pixi. I am trying to render a single sprite on the scene

I am using the asset loader to load in a texture, create a sprite, and render it to the screen. i am receiving no errors but the canvas just stays blank. i should mention that im using webpack. here’s my code:

index.js

    import * as PIXI from 'pixi.js'
    import { roomSceneManifest } from './image_imports.js'

    async function loadAssets (){
      const app = new PIXI.Application()
      await app.init({ width: 800, height: 600 });
      document.body.appendChild(app.canvas);
    
      PIXI.Assets.init({manifest: roomSceneManifest})
    
      const assets = await PIXI.Assets.loadBundle('png');
      console.log(assets)
      const bg = PIXI.Sprite.from(assets.BackgroundImg);
      console.log(bg)
      bg.anchor.set(0.5);
      bg.x = app.screen.width / 2;
      bg.y = app.screen.height / 2;
      app.stage.addChild(bg);
    }

    loadAssets()




    ./image_imports.js

    export const roomSceneManifest =  {
       "bundles":[
          {
             "name":"png",
             "assets":[
                {
                   "alias":"BackgroundImg",
                   "src":BackgroundImg
                }
             ]
          }
       ]
    }