Allow tab navigation for a button within a div. If the div is focussed?

I am having a component like this: (Code Sandbox: https://codesandbox.io/s/boring-platform-1ry6b2?file=/src/App.js)
enter image description here

The green part is div. Here’s my code:

import { useState } from "react";
import "./styles.css";

export default function App() {
  const [insideApp, setInsideApp] = useState(false);
  return (
    <div onFocus={() => setInsideApp(true)} onBlur={() => setInsideApp(false)}>
      <div className="App">
        <input className="input" />
        {insideApp && <button>Show Button</button>}
      </div>
      <p>Out of Box content</p>
    </div>
  );
}

/* css */
.App {
  display: flex;
  border: 2px solid aqua;
  align-items: center;
  column-gap: 2vw;
  padding: 2rem;
}

.App:focus-within {
  border: 2px solid lime;
}

.input {
  flex: auto;
}

What I want ideally is when I navigate to the button through tab it should get highlighted as shown below:

enter image description here

However since I am rendering the button conditionally I am losing focus. Can someone help me come up with some innovative idea to achieve the same? I want the div to change to lime when its focussed and then do a tab navigation such that it detects input as well as button.

Also I want button to be only shown when focus is within the div.

UrlFetchApp.fetch in javascript is returning html but with one character missing

I’m using UrlFetchApp.fetch(link).getContentText(); and then looking for a csv file download link within the page code.
All looks fine, except it seems the url is missing the last character for the download link.

Original htm section looks like:

window.location.href = '/DownloadReport/Download?DownloadFile=KthLRtKyqfo%2FlRepJnU7H0KpCPs13Y088O6QCQ9pjsFHsZX40P3imlTGya5Six7K';

But the response I get from UrlFetchApp is missing the K. It happens the same for all different pages, the final character is missing.

window.location.href = '/DownloadReport/Download?DownloadFile=KthLRtKyqfo%2FlRepJnU7H0KpCPs13Y088O6QCQ9pjsFHsZX40P3imlTGya5Six7';

What I’m doing with it – In google sheets, I’m using it to grab a download link from an email, that link then opens the download page and I need to the actual download url to get the csv and it’s data.

Cypress: How to get elements from a variable with HTML?

I’m currently working on API testing. The API that I’m testing is returning an HTML body. How do I get an element from the response body? If I visit the link, it returns an iframe and I cannot access it properly inside cy.origin.

How to get the https://test-develop.test.net/download/cd668080-be63-11ed-8328-41d4c5da193d or the XudSov7Y6JDm ? I’ve been going through this for hours but can’t seem to find a solution :/

var message = `<html>

<body style="background-color:#f5f5f5;font-family:'Open Sans',sans-serif;padding:24px 0;">
    <div style="margin:0 auto 24px auto;text-align:center">

        <img width="130" src="cid:quipper_logo" alt="School LINK" />

  </div>
        <hr style="border:none;" />
        <div style="margin:12px auto;max-width:540px;background-color:white;border:1px #dcdcdc solid;padding:20px;">
            <p><strong>** This email is automatically generated. Please do not reply. **</strong></p>


            <p>Your Excel spreadsheet for is ready to download.</p>



            <p>Please note: you will need to enter the supplied username and password to download the file.</p>




            <p><strong>Download:</strong> <a
                    href="https://test-develop.test.net/download/cd668080-be63-11ed-8328-41d4c5da193d">https://test-develop.test.net/download/cd668080-be63-11ed-8328-41d4c5da193d</a>
            </p>


            <p>Username: [email protected]</p>
            <p>Password: XudSov7Y6JDm</p>



        </div>
</body>

</html>`

.replace() won’t replace every instance despite /g

So, I’ve got two problems with my javascript code. I’ll try to make it as short as possible and only copy parts that are necessary for the problem.

I have this html code (it’s not my fault that every li looks different):

    <li>
        <span style="font-family:arial, helvetica, sans-serif;">Siehe <a href="Link 1" rel="">Text 1</a>.</span>
    </li>
    <li>
        <span style="font-family:arial, helvetica, sans-serif;">Siehe</span> <a href="Link 1" rel="">Text 2</a>.<span style="font-family:arial, helvetica, sans-serif;"> </span>
    </li>
    <li>
        Siehe <a href="Link 1" rel="">Text 3</a>.
    </li>

And here comes the necessary javascript code for my problems. First, I delete every span element. After that I want to replace the “a href” parts and increase the number of the new string.

var neu = document.getElementById("ausgabe").value;             
var nummer = 0;
function getNextDlcNumber() {
    return ++nummer;
}

var ersetzen = neu
.replace(/<span.*?>(.*?)</span>/g, "$1") // Gets rid of every span
.replace(/s<li>nssSiehes*<a href=".*?" rel="">(.*?)</a>.ns</li>/g, "t<li>nttSiehe <a class="trophiesAnkerLink" href="#dlc" + getNextDlcNumber() + "" rel="">$1</a>.nt</li>"); // Replaces a href with increasing dlc numbers

document.getElementById("ausgabe").value = ersetzen;

There are two problems with this:

  1. The first and third “a href” are replaced successfully. But the second one isn’t and I can’t figure out why. I think it has something to do with the span tag between “Siehe” and the start of the “a” tag, however the span should get deleted due to the first replace so I’m not sure if that’s what causes the problem. I tried using “Siehes*<a”, “Siehe <a” as well as an or using | that contained the “” but none of that worked.

  2. The number after “#dlc” isn’t increasing, it just stays at “#dlc1” even for the third one. Do I need to do that in a different way?

Here’s the output after using the js:

    <li>
        Siehe <a class="trophiesAnkerLink" href="#dlc1" rel="">Text 1</a>.
    </li>
    <li>
        Siehe <a href="Link 1" rel="">Text 2</a>. 
    </li>
    <li>
        Siehe <a class="trophiesAnkerLink" href="#dlc1" rel="">Text 3</a>.
    </li>

I hope I posted every necessary information. If not, I can provide more. Thanks for your help in advance 🙂

Brython python to javascript converter

I want to create a tool using brython that translates python to js without running it. I know that there is a way to do it (i was doing some research: http://www.brython.info/tests/precompile.html or Python to JavaScript converter) but still i can’t make it. The goal is to make html file like this below, but instead of copying and pasting same value to the second textarea actualy convert it to javascript?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <textarea name="input" id="input" cols="30" rows="10">Here write your python code...</textarea>
    <button id="convert" onclick="convert()">Convert</button>
    <textarea name="output" id="output" cols="30" rows="10">Here you will receive your javascript code...</textarea>

    <script>
        function convert(content)
        {
            var input = document.getElementById("input");
            var output = document.getElementById("output");
            
            output.innerHTML = input.innerHTML;
        }
    </script>

</body>
</html>

I tried to make python to js converter without frameworks such as Flask or Django, obviously it won’t be a problem If you will suggest to use another js library for this like pyjs, javascrypthon or anything else.

use pinia outside of component in ViteSSG

I’m working on a Vue.js project build using ViteSse template, I wanna use one of my Pinia stores named notificationStore outside of the setup component but I get getActivePinia was called with no active Pinia. Did you forget to install pinia error when I run dev command It’s behavior is so strange becasue it’s not occured if I add useNotificationStore after dev server loaded and It woks well but when useNotificationStore exisit in my ts file and run dev command it raise error.

here is my setup:

main.ts

import { ViteSSG } from 'vite-ssg'
import { setupLayouts } from 'virtual:generated-layouts'
import { useAuth, useOidcStore } from 'vue3-oidc'
import type { UserModule } from './types'
import App from './app.vue'
import generatedRoutes from '~pages'
import './assets/styles/style.scss'
import '@/config/oidc'
const routes = setupLayouts(generatedRoutes)
const { autoAuthenticate } = useAuth()
const { state } = useOidcStore()
const isMocking = import.meta.env.VITE_API_MOCKING_ENABLED
if (isMocking === 'true') {
  const browser = await import('~/mocks/browser') as any
  browser.worker.start({ onUnhandledRequest: 'bypass' })
}

export const createApp = ViteSSG(
  App,
  { routes, base: import.meta.env.BASE_URL },
  async (ctx) => {
    Object.values(import.meta.glob<{ install: UserModule }>('./modules/*.ts', { eager: true }))
      .forEach(i => {
        i.install?.(ctx)
      })


    const DEFAULT_TITLE = 'Dashboard'
    ctx.router.beforeEach((to) => {
      if (!state.value.user) {
        autoAuthenticate()
      }
      let title = DEFAULT_TITLE
      if (to.meta.title)
        title = `${to.meta.title} - ${title}`

      document.title = title
    })
  },
)

notification.store.ts

import { acceptHMRUpdate, defineStore } from 'pinia'

interface NotificationState {
  messages: Array<Notification>
}
export interface Notification {
  type?: 'error' | 'info' | 'success' | 'warning'
  timeout?: number
  permanent?: boolean
  message: string
  hideAfterRouting?: boolean
  validationErrors?: Array<string>
  shown?: boolean
}

export const useNotificationsStore = defineStore('notification', {
  state: (): NotificationState => ({
    messages: [],
  }),
  actions: {
    addNotification(message: Notification) {
      if (isDuplicatedMessage(this.messages, message))
        return

      message.timeout = message.timeout || 3000
      message.shown = true
      this.messages.push(message)
    },
    remove(index: number) {
      this.messages.splice(index, 1)
    },
    clearAfterRoute() {
      const visibleNotification = this.messages.filter(
        item => item.hideAfterRouting === false,
      )
      this.messages = visibleNotification
    },
  },
})

function isDuplicatedMessage(messages: Notification[], message: Notification): boolean {
  if (!messages.length)
    return false
  return (messages[messages.length - 1].message === message.message)
}

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useNotificationsStore, import.meta.hot))

http-client.ts

import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import axios from 'axios'
import tokenService from './token.service'
import { useNotificationsStore } from '~/store/notification.store'
const notification = useNotificationsStore()
const httpClient: AxiosInstance
  = axios.create({
    baseURL: `${import.meta.env.VITE_APP_API_URL}/`,
    headers: {
      'Content-Type': 'application/json',
    },
  })

httpClient.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = tokenService.getLocalAccessToken()
    if (token && config.headers)
      config.headers.Authorization = `Bearer ${token}`

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)
httpClient.interceptors.response.use(
  (response) => {
    if (response.config.method !== 'get') {
      const successMsg = 'operation successfully completed'
      notification.addNotification({ type: 'success', message: successMsg })
    }
    return response
  },
  (error) => {
    if (error.message === 'Network Error') {
      notification.addNotification({ type: 'error', message: 'Network Error' })
      return Promise.reject(error)
    }
    let errorMessage = ''
    const validationErrors = getValidationErrors(error)
    errorMessage = getErrorMessage(error)
    notification.addNotification({ type: 'error', message: errorMessage, validationErrors, hideAfterRouting: false })
  }
)

Vite.config.ts

// Plugins

// Utilities
import path from 'path'
import { URL, fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'

import vuetify from 'vite-plugin-vuetify'
import Vue from '@vitejs/plugin-vue'
import Pages from 'vite-plugin-pages'
import Layouts from 'vite-plugin-vue-layouts'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { VitePWA } from 'vite-plugin-pwa'
import VueI18n from '@intlify/vite-plugin-vue-i18n'
import Inspect from 'vite-plugin-inspect'

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 9080,
    host: true,
    hmr: {
      host: 'localhost',
    },
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      '~': fileURLToPath(new URL('./src', import.meta.url)),
    },
    extensions: [
      '.js',
      '.json',
      '.jsx',
      '.mjs',
      '.ts',
      '.tsx',
      '.vue',
    ],
  },
  plugins: [
    Vue({
      include: [/.vue$/],
      reactivityTransform: true,
    }),
    vuetify({
      autoImport: true,
    }),
    // https://github.com/hannoeru/vite-plugin-pages
    Pages({
      extensions: ['vue'],
      dirs: [
        { dir: 'src/router/views', baseRoute: '' },
      ],
      extendRoute: (route) => {
        if (route.path === '/')
          return { ...route, redirect: '/Dashboard' }

        return route
      },

    }),

    // https://github.com/JohnCampionJr/vite-plugin-vue-layouts
    Layouts({
      layoutsDirs: ['src/router/layouts'],
    }),

    // https://github.com/antfu/unplugin-auto-import
    AutoImport({
      imports: [
        'vue',
        'vue-router',
        'vue-i18n',
        'vue/macros',
        '@vueuse/head',
        '@vueuse/core',
      ],
      dts: 'src/auto-imports.d.ts',
      dirs: [
        'src/composable',
        'src/store',
      ],
      vueTemplate: true,
    }),

    // https://github.com/antfu/unplugin-vue-components
    Components({
      extensions: ['vue'],
      include: [/.vue$/, /.vue?vue/],
      dts: 'src/components.d.ts',
      deep: true,
    }),  

    // https://github.com/intlify/bundle-tools/tree/main/packages/vite-plugin-vue-i18n
    VueI18n({
      runtimeOnly: true,
      compositionOnly: true,
      include: [path.resolve(__dirname, 'locales/**')],
    }),

    // https://github.com/antfu/vite-plugin-inspect
    // Visit http://localhost:3333/__inspect/ to see the inspector
    Inspect(),
  ],

  // https://github.com/vitest-dev/vitest
  // test: {
  //   include: ['test/**/*.test.ts'],
  //   environment: 'jsdom',
  //   deps: {
  //     inline: ['@vue', '@vueuse', 'vue-demi'],
  //   },
  // },

  // https://github.com/antfu/vite-ssg
  ssgOptions: {
    script: 'sync',
    formatting: 'minify',
    // onFinished() { generateSitemap() },
  },

  ssr: {
    // TODO: workaround until they support native ESM
    noExternal: ['workbox-window', /vue-i18n/],
  },

  define: { 'process.env': {} },
})


I have traced issue with some logging and finded that it occured before createApp get executed that initate pinia and there was not active pinia on that time. I expected createApp in main.ts have been executed before all

thanks in advance

How can I get the actual file in an , to be displayed in the tag with JavaScript?

I have an input tag with type=file and I want to take the data it selects to display inside a textarea tag. I do not want to display just the file title but the entire file. Like how uploading attachments to emails before they are sent works.
How do I do this with javascript? There is no backend or server-side code in this work yet. I have tried to change the value but it only displayed the object type of the file to the textarea

let textfile = document.getElementById('file')
let textarea = document.getElementById('compose')
console.log(textarea);

textfile.addEventListener('change', (e) =>{
    let fil = e.target.files[0];

    if(fil){
        let reader = new FileReader();
        reader.readAsDataURL(fil);
    }

    textarea.value = fil 
})

Rollup modules but keep all variables global

I will simplify code for my problem. So let’s assume I have in module1.js

export class MyClass { };

and in index.js

import { MyClass } from './module1.js'

var X = MyClass();

Next i want to bundle index.js with rollup in such way that the result file contents should look like this


class MyClass { };
var X = MyClass();

My goal is to put the result file into script tag and to be able to access all declared variables in global space e.g window.MyClass and window.X from other scripts.

Is there any rollup options or plugins for this purpose?

To Add New Row in lightning datatable While clicking on New Button getting undefined

I am trying to add Row when clicking on New Button in lightning Data table.
Created lightning-button in HTML and call the method to js.While trying to click New button getting Undefined.
Sample Code:

 **Test.html:**

    <template>
    <lightning-card >
    <lightning-button-group>
          <lightning-button label="New" onclick={addRow}></lightning-button>
    </lightning-button-group>
    <lightning-datatable data={strpData} columns={columns} onsave={saveHandleAction}
      draft-values={fldsItemValues} key-field="Id" onrowselection={getSelectedRows}>
         </lightning-datatable>
    </lightning-card >
    </template>
    
**Test.JS:**

import { LightningElement, track, api, wire } from 'lwc';
const columns = [
    {label:'NUMBER', fieldName:'Name' },
    {label: 'Test1', fieldName: 'Test1'}
];
export default class Test extends LightningElement {
@track columns = columns;
@track strpData = [];
addRow() {  
       // this.isShowModal = true;
       console.log('>>>add row>>>');
        const newRow ={'Name':'','Test1':''};
        console.log('>>>new row>>>'+this.newRow);
        this.strpData.push(newRow);
        console.log('strpData ==>>> '+JSON.stringify(strpData));
    }
}

Getting console log error:

enter image description here

Hope someone could give some help. Thanks.

Incorrect date returned

Tell. Why is the wrong date returned to me when MANUALly entering the date in new Date()?
If you choose through the calendar, then everything works

const newDate = new Date(2022,10,10)

Expected to return October 10, but is returning 2022-11-09

Javascript reference a function with a string (in a module)

I have a JS file loaded into the head as a module:

<script type="module" src="/js/main.js"></script> 

In the main.js file I have a number of function that need to be called dynamically, depending on what instance of a button is clicked.

The normal solution would be to use window["my_func"] but this doesn’t work in a module context.

I can get around this by assigning each function to the window i.e window.my_func = my_func; but is there something I’m missing here? Is there something similar to window["my_func"] that works in the module scope?

how to use Filter function in combination with startsWith function?

I have an array populated with countries by ISO code:

const immatureMarkets = ["ID", "TN", "MY", "PH", "IN", "BD"];

I need to filter this array in order to pass a prop value only if the geoLocation of the user is starting with one of these ISO codes.

This is my solution but it’s not working as the value returned by startsWith is always false in console:

flagImg={
    immatureMarkets.filter((market) =>
      market.startsWith(geoLocation)
    )
      ? countryByGeo?.flagImage?.url
      : null
  }

This is the value of geoLocation using VPN in Malaysia:

geooLocation Value

Even if the geoLocation is starting with MY, market.startsWith(geoLocation) always returns a false value