Setting default zoom in Thunderbird 91+ using JS

While Mozilla Firefox at last has gained a preference which allows to set Default Zoom level, Thunderbird still haven’t got it. This is significant accessibility issue.
There exist a hack which allows to set the desired zoom level using Browser Console in Firefox, it is described here. I supposed that similar approach would work in Thunderbird and found the working command:

ZoomManager.setZoomForBrowser(getBrowser(), 1.2);

If this command is run in Error Console (analog of Browser Console in Firefox and it can be launched by the same shortcut Ctrl+Shift+J), then 120% zoom will be applied to the letter preview pane (at least).
Now the problem is to run this command at Thunderbird start. I installed userChromeJS extension which is developed to support Thunderbird version 91+ and which will “load the contents of chrome/userChrome.js from the user’s profile directory every time a window is opened” as is said in its description. Then I added the next code, found here into chrome/userChrome.js:


if (location == "chrome://messenger/content/messenger.xul") {
  setTimeout(function() {
    ZoomManager.setZoomForBrowser(getBrowser(), 1.2);
  }, 0);
}

})();

But it doesn’t work, zoom isn’t applied to the preview pane as when I run this command manually.
Maybe this code is wrong? I’m not that good in JS to fix it myself.

Can we consider this JS code a linked list?

I’ve been wondering if we can consider this JS code a liked list because it looks like an infinity nested object that is pointing always at the same value.

    const linkedList = {
     add(){return linkedList}
    };
conosole.log(linkedList.add().add().add());

How to get value of a component to another component

I am creating a Project where I need to get value of a component state value to another component.

How can I get the value?

Information

  1. Both are functional component.
  2. I need to send data from A (state) to B(state).
  3. A state data are set from react dropdown menu.Which is a button.
  4. I don’t use Link or Route to A dropdown that’s why I can’t get it with useParams()
  5. I need to set value in B component which will fetch data with passing language.
  6. I have import all needed things & don’t have any warnings & error.

Code of component A

  1. Send value from this language state to B
const A = () => {
    const [language, setLanguage] = useState('en');
    
    return (
        <Navbar expand="xl" bg='light' expand={false}>
            <Container>
                <DropdownButton id="dropdown-basic-button" title={<MdOutlineLanguage />}>
                    <Dropdown.Item as="button" onClick={() => setLanguage('en')}>English</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('ar')}>العربية</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('bn')}>বাংলা</Dropdown.Item>
                </DropdownButton>
            </Container>
        </Navbar>
    )
};

export default A

Code of Component B

  1. I need to get here A state value & set it to B state. Then pass to useGetDataQuery & fetch data.
const B = () => {
    let [language, setLanguage] = useState('en')
    const { data } = useGetDataQuery({language })
    
    return (
        <>
            
        </>
    )
}
export default B

Javascript toString() forces ASCII character to change to hex

I’m having a little problem with toString(), when I’m changing the whole function to string to match with regex, toString() changes special characters to HEX, but I need them to stay as they were original in the function as I need to match them later original to original with search and replace function.

Here is an example.

// I'm matching XX.g1("ABV", JU)
function wd () {
 var Dq = document["createElement"](XX.g1("ABV", JU));

}
const regex = / /
const l = wd.toString().match(regex);
let obj = {};
for (let i = 0; i < l.length; i++) {
  const e = l[i]
  console.log(e)
  obj[e] = eval(e)
}

returning XX.g1("Au0017BV", JU) but I need it to be formated as on the picture
original

{
    "XX.g1("Au0017BV", JU)": "span",
}

Show/Hide divs based on Time/Opening Hours

I am trying to show/hide divs based on opening hours.

The div .open contains the headline “Our store is open” and the other div .closed contains the headline “Our store is close”.

The store has the following opening hours:

Monday: 09:00-12:00 & 14:00-18:00

Tuesday: 08:30-12:00 & 13:30-18:00

Wednesday: 09:00-12:00 & 14:30-18:00

Thursday: 09:00-12:00 & 14:00-18:00

Friday: 09:00-12:00 & 14:30-18:00

Saturday: 08:00-11:30

Sunday: Closed

The timezone is Germany (UTC+1).

So during the opening hours the div with the class .open should be displayed and the other div with the class .close should be hidden.

During the closed times the div with the class .close should be displayed and the div with the class .open should be hidden.

I also tried to add special days when the store is closed for a whole day. E.g. December 24 & December 26.

I have tried so much but always failed, I hope someone can help me with this.
Really appreciate any comment on this as i search for a solution for hours now.

How to I traverse/loop through a tree of arrays?

I have my tree which a want to traverse through, each subtree might have different length:


const Tree = [
  {
    data: true,
    subTrees: [{
      data: true, subTrees: [{ data: true, subTrees: [] }]
    }]
  },
  {
    data: true,
    subTrees: [{
      data: true, subTrees: []
    }]
  },
  {
    data: true,
    subTrees: [{
      data: true, subTrees: [{ data: true, subTrees: [{ data: true, subTrees: [] }] }]
    }]
  },
  {
    data: true,
    subTrees: [{
      data: true, subTrees: [{ data: true, subTrees: [] }]
    }]
  }
]

How do I loop through each and every subTree so I can access the data in each node?

This is what I have now:


function traverseTree(currentTree) {

  for (let i = 0; i < currentTree.length; i++) {
    
    // do something

    traverseTree(currentTree[i])

  }

}

Autocomplete – populating textbox when clicked issue Javascript

I’ve been working on the autocomplete feature for a webpage. Autocomplete function is running fine, but whenever I click on one of the suggestions, it only selects the first thing on the list as it populates the textbox. Even after clicking, for instance, the second or third suggestion, it only selects the first suggestion. The first event is the autocomplete while the second event is the click function and populating the text box when item is selected. My issue is the click event, I’m thinking of creating another loop, like the one for the autocomplete event. However, would it be redundant to do that in the click event as well? Here’s the code that I’m working on. Please, no JQuery, innerHTML or innerText. I’m strictly using pure JS. Thank you!

document .getElementById("title").addEventListener("keyup", function autoComplete(e) {
  let searchvalue = e.target.value;
  let suggestionBox = document.querySelector(".suggestions");
  suggestionBox.textContent = "";

  if (searchvalue.length > 2) {
    let titles = movData.filter((title) => {
      return title.title.toLowerCase().startsWith(searchvalue);
    });
    titles.forEach(function (suggested) {
      let div = document.createElement("li");
      div.textContent = suggested.title;
      suggestionBox.append(div);
    });
    if (searchvalue === "") {
      suggestionBox.textContent = "";
    }
  }
});

document.querySelector("#header-mobi").addEventListener("click", function select() {
  if (document.querySelector(".suggestions > li")) {
    document.getElementById("title").value =
      document.querySelector(".suggestions > li").textContent;
  }
});

<div id="main">
  <div class="form-center">
    <form id="header-mobi">
      <div class="header">
        <p>Movie Browser</p><br /><br />
      </div>
      <h1 id="title1">Enter Movie Title:</h1>
      <input type="text" title="title" id="title" name="title" placeholder="Movie Title"
      />
      <div class="suggestions"></div>
      <br />
      <button type="button" id="matching-btn" class="button button1">
        Show Matching Movies
      </button>
      <button type="button" id="all-btn" class="button button2">
        Show All Movies
      </button>
    </form>
  </div>

Change quantity of product in django ecommerce website? DJANGO

It’s not giving an error. The quantity is being changed only in the first product, even if when I press arrow of second product, the quantity of first product is being changed.
cart.js

var changeQ = document.getElementsByClassName('increase')


for (i = 0; i < changeQ.length; i++) {
    changeQ[i].addEventListener('click', function(){
        var productId = this.dataset.product
        var action = this.dataset.action
        console.log('productId:', productId, 'Action:', action)
        
        
        if (action == 'plus'){
            Increase(productId, action)
        }
        else if(action=='minus'){
            Decrease(productId, action)
        }
    })
}

function Increase(productId,action){
    console.log('Increase')
    var quantity = Number(document.getElementById("quantity").value);
    quantity = quantity+1;
    document.getElementById("quantity").value = quantity;
    console.log(quantity);
}

function Decrease(productId,action){
    var quantity = Number(document.getElementById("quantity").value);
    console.log('Decrease')
    quantity = quantity-1;
    document.getElementById("quantity").value=quantity;

}

template

<div class="counter">
    <div class="arrow-up increase" id="arrow-up" data-product="{{item.product.id}}" data-action="plus" ><i class="fa fa-arrow-up"></i></div>
    <div class="quantity"><input type="number" id="quantity" value="1"></div>
    <div class="arrow-down increase" id="arrow-down" data-product="{{item.product.id}}" data-action="minus"><i class="fa fa-arrow-down"></i></div>
  
  </div>

It’s in Django. So what can I do to indicate the specific product. Can someone help me to solve this problem, please!

Can you capture both audio input and output as one audio stream in JavaScript?

I am aware of the MediaStream Recording API but after some research I am unsure if I can capture both input and output within a JavaScript application.

Essentially I want to capture both my own microphone and the audio in which I receive (essentially the audio from another users microphone).

Any help would be greatly appreciated in sending me in the right direction!

Why Reject of Promise giving undefined error?

I have a set of list with checkboxes, when i click 5 checkboxes an alert message to be displayed congrates you have selected 5 options. i have to do the validation using promise. If i am not using reject, it is working fine. but if i add the code as given below, ‘reject’ code is executed and displaying error as ‘undefined’.please any one help, where i have gone wrong?

 let clickvalidation = new Promise(function(resolve, reject) {
          $('input[type=checkbox][id=chk1]').change(function() {
                if ($(this).is(':checked')) {
                  noOfClick++;
                  if(noOfClick==5){ 
                   resolve();
                  }else{
                  reject();
                  }       
                }
            });
        });
          
           
        clickvalidation
            .then(function () {
                console.log('Success, You are a GEEK');
                alert(`Congrats 5 tasks have been successfully completed`);
              
            })
            .catch(function (e) {
                console.log(e.stack);
            });

Manipulating data point in chart.js external tooltip

I’m using Chart.js to display some financial data in a pie chart, along with external tooltips. The data in the tooltip is displayed currently like this:

“Invoiceable: 1,202.5”

What I want is to firstly round the number to 1,200, and then add a ‘£’ sign before the data point so it reads:

“Invoiceable: £1,200”

I’m struggling to work out how to do this in this code below. Can anyone help?

 tooltip: {
            // Disable the on-canvas tooltip
            enabled: false,

            external: function(context) {
                // Tooltip Element
                let tooltipEl = document.getElementById('chartjs-tooltip');

                // Create element on first render
                if (!tooltipEl) {
                    tooltipEl = document.createElement('div');
                    tooltipEl.id = 'chartjs-tooltip';
                    tooltipEl.innerHTML = '<table></table>';
                    document.body.appendChild(tooltipEl);
                }

                // Hide if no tooltip
                const tooltipModel = context.tooltip;
                if (tooltipModel.opacity === 0) {
                    tooltipEl.style.opacity = 0;
                    return;
                }

                // Set caret Position
                tooltipEl.classList.remove('above', 'below', 'no-transform');
                if (tooltipModel.yAlign) {
                    tooltipEl.classList.add(tooltipModel.yAlign);
                } else {
                    tooltipEl.classList.add('no-transform');
                }

                function getBody(bodyItem) {
                     return bodyItem.lines;
                }

                // Set Text
                if (tooltipModel.body) {

                    const titleLines = tooltipModel.title || [];
                    const bodyLines = tooltipModel.body.map(getBody);

                    let innerHtml = '<thead>';

                    titleLines.forEach(function(title) {
                        innerHtml += '<tr><th>' + title + '</th></tr>';
                    });
                    innerHtml += '</thead><tbody>';

                    bodyLines.forEach(function(body, i) {
                        innerHtml += '<tr><td><div class="tooltip">'+ body + '</div></td></tr>';
                    });
                    innerHtml += '</tbody>';

                    let tableRoot = tooltipEl.querySelector('table');
                    tableRoot.innerHTML = innerHtml;
                }

                const position = context.chart.canvas.getBoundingClientRect();
                const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);

                // Display, position, and set styles for font
                tooltipEl.style.opacity = .8;
                tooltipEl.style.position = 'absolute';
                tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
                tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
                tooltipEl.style.font = bodyFont.string;
                tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
                tooltipEl.style.pointerEvents = 'none';
            }
        }

FTR – I copied the above code from chart.js, which made it work, but I don’t presume to understand it for a second!

component input with variable tags and text

I need an input component where I can insert text and when I enter a special character, a window appears with a choice of variables and it will be inserted as a tag, and this variable tag can be inserted anywhere in the text. As far as I understand, this should be done with contentEditable.

all I could do is such an input, where I put the $ symbol only at the end, and not a tag is added, but text:
enter image description here

I found many examples where there is just adding tags (https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/), but I didn’t find such a component where tags are mixed with text, can anyone see this?

import { useState } from 'react'

import classNames from 'classnames'
import ContentEditable from 'react-contenteditable'

import { useAppSelector } from '../../app/hooks'
import { selectVariables } from '../../redux/reducers/variables'

import styles from '../../stylesheets/components/common/InputVariable.module.scss'

export const InputVariable = ({ className, label, onChange, value }: any) => {
  const { variables } = useAppSelector(selectVariables)
  const [symbol, symbolSet] = useState(false)

  const handleChange = (e: any) => {
    const str = e.target.value

    onChange(str)

    if (str.charAt(str.length - 1) === '$') {
      symbolSet(true)
    } else {
      symbolSet(false)
    }
  }

  const handleClickVariable = (variable: any) => {
    const newStr = `${value.substring(0, value.length - 1)}{{${variable.id}}}`

    onChange(newStr)
    symbolSet(false)
  }

  const onPaste = (e: any) => {
    e.preventDefault()
    const text = e.clipboardData.getData('text/plain')

    console.log(text)
  }

  return (
    <div className={classNames(styles.inputVariable, className)}>
      <span className={styles.label}>{label}</span>
      <ContentEditable
        className={styles.root}
        html={value}
        disabled={false}
        onChange={handleChange}
        onPaste={onPaste}
      />
      {symbol && (
        <div className={styles.variables}>
          {variables &&
            variables.map((variable: any) => (
              <div key={variable.id} onClick={() => handleClickVariable(variable)} className={styles.variable}>
                {variable.name}
              </div>
            ))}
        </div>
      )}
    </div>
  )
}

export default InputVariable

Error initializing Alchemy Provider in next.js using alchemyUrl inside env.local

I want to init alchemy json Provider in next.js

the alchemy url with key is stored inside env.local like so-

ALCHEMY_URL=https://polygon-mumbai.g.alchemy.com/v2/myAlchemyKey

page: /nft

 const alchemyUrl = process.env.ALCHEMY_URL

 console.log("** ethersAlchemyProvider **")
 const ethersAlchemyProvider =  new 
 ethers.providers.JsonRpcProvider(alchemyUrl)
 // console.log(ALCHEMY_URL)
 //console.log(ethersAlchemyProvider)

If the above is not possible in next.js, can you show me how I should init ethers provider serverSide and pass it inside the /nft page as prop, this what I tried-

 export async function getServerSideProps() {
  var ethers = require('ethers')

   // init alchemy provider here
  const ethersAlchemyProvider =  new ethers.providers.JsonRpcProvider(process.env.ALCHEMY_URL)
  
   // Pass data to the page via props
   return { props: { ethersAlchemyProvider } }
 }

It gives me this error-

enter image description here

Basically I want to initialize the ethers-provider using that alchemy-key inside env.local.

am using “next”: “12.0.10”

useEffect not rerendering parent component when its state changes from a child call, why?

I have a parent component with specifies state using hooks and its watching the state change via the dependency array in useEffect of the parent, (also here watching the props change in the child)
When i change the parent state via the components do not re-render but the state has the new value saved
Im kinda puzzled to why is this happening, any ideas?

here are the parent/child components:

PARENT

import ScopeView from './ScopeView'

export default function ScopeController() { 
const [selectedPhases, setSelectedPhases] = useState({})
.
.

  function handleSelectedPhases(value) {
    console.log(value, 'clicked phase')
    setSelectedPhases(value)
  }

useEffect(() => {
    if (regions.length && !regionId) setRegionId(regions[0]?.id)
    console.log(selectedPhases, 'useEffect')
  }, [selectedPhases])
}
.
.
return (
<ScopeView
      selectedPhases={selectedPhases}
      onClick={value => handleSelectedPhases(value)}
    />
)

CHILD

import React, { useState, useEffect } from 'react'


export default function ScopeView({
  selectedPhases,
  onClick,
  
}) {
  useEffect(() => {
    console.log(selectedPhases, 'child useEffect trigger')
    setSelectedCell(selectedPhases)
  }, [selectedPhases])
  return (
    <>
      <div style={{ width: '100%'
        <div style={{ width: '100%' }}>
   .
   .
   .
                    return (
                      <div className={cl.servicesRow} key={s.id}>
                       
                        <ClickableButton
                          phases={phases}
                          serviceId={s.id}
                          selectedPhases={selectedPhases}
                          isPhasesService={isPhasesService}
                          phasesService={phasesService}
                          onClick={onClick}
/>
                     
      </div>
  )
}