Does JavaScript ‘Set’ work for HTMLStyleElement objects?

In my website there are some duplicated <Style> elements in DOM. I am trying to use a Set in JavaScript to do some de-duplication for these elements. The code to generate non-dup elements is something like:

const CSSCache = new Set<HTMLStyleElement>();
const styles = document.getElementsByTagName('style');
for (let i = 0; i < styles.length; i++) {
   CSSCache.add(styles[i] as HTMLStyleElement);
}

I am wondering if the JavaScript Set able to unique-fy these HTMLStyleElement objects.

Also, some of these elelment doesn’t have any content, e.g. <style></style> but they have rules in element.sheet.cssRules inserted with insertRule (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule). I am wondering if Set works for these types of Style as well.

bootstrap not showing dropdown

I have a bootstrap form that I have added a dropdown list. When I click on the dropdown I see the list, but when I click on it doesn’t show as selected it still shows “select Domain” all the time. I found this link

https://www.codeply.com/go/pTWA3jYWEv/bootstrap-bootstrap-dropdown-selected-value

I have modified it, but I am missing something cause it is not working for me.

<div class="form-group">
<div class="dropdown">
  <button class="btn btn-primary btn-user btn-block dropdown-toggle" type="button"
          id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select Domain
      <span class="caret"></span>
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item">Corp</a>
    <a class="dropdown-item">Domain2</a>
    <a class="dropdown-item">Domain3</a>
    <a class="dropdown-item">Local</a>
  </div>
</div>
</div>


<script type="text/javascript">
$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.dropdown').find('.btn btn-primary btn-user btn-block dropdown-toggle').html(selText+' <span class="caret"></span>');
});
</script>

How to upload HTML Canvas Image to Shopify/ Cloudinary /or other Media Manager?

I’ve been struggling with this for a while, but let me explain the context first.

I’m developing a very simple ‘Product customizer’ using vanilla Javascript for a Shopify merchant.

You can check it here

The customer uploads an image, the image is rendered in the HTML canvas and then placed where desired.

I need to send the Canvas resulting image to the merchant.

I tried appending a canvas blob to the Shopify form like this

let dataURI = canvas.toDataURL();
let blob = dataURItoBlob(dataURI);
let formData = document.querySelector('#shopify-form');
formData.append('file', blob);

And nothing…

So I tried using Cloudinary client-side upload API following this YouTube tutorial.

and I came up with this, sending the request with axios:

addToCartBtn.addEventListener('click', function (e) {
    // e.preventDefault();
    dataURI = canvas.toDataURL();
    let blob = dataURItoBlob(dataURI);
    let formData = new FormData();
    formData.append('file', blob);
    formData.append('upload_preset', cloudinaryConfig.preset)

    axios({
        url: cloudinaryConfig.api,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }).then(function (res) {
        console.log(res);
    }).catch(function (err) {
        console.error(err);
    })
})

So when the customer clicks the Add To Cart button, the canvas image can be uploaded to Cloudinary.

But it results in a 400 – Bad request, clearly I’m messing up somewhere. Please help.

In summary, I need help with either sending the Canvas Image through a shopify order o uploading it to Cloudinary (or any other media manager).

Thanks in advance.

Vue.js. Send get/post request with headers and parameners

All I want is to create LinkedIn login component. I cannot find any information about headers and parameters. Can anyone tell me how to send GET or POST request with parameters and headers?

Here’s my code with parameters. Any idea where should be headers?

await axios.get('https://www.linkedin.com/oauth/v2/authorization', {
   response_type: 'code',
   client_id: 'MY_CODE_HERE',
   redirect_uri: 'http://localhost:8080/auth/login',
   scope: 'r_liteprofile r_emailaddress w_member_social',
}).then(response => {
   console.log("INFO: " + response);
}).catch(error => {
   console.log("ERROR: " + error);
});
``

redux toolkit state is not changing

When I send request I got my data back in json and I can see it when console.log().
But when I try to change my state, it’s not changing. Can you guys please help me to understand why? Don’t judge too hard I am still learning. Thank you

Here is my code

export const login = createAsyncThunk(
     'auth/login',
     async (user) => {
          try {
               const response = await loginUser(user);
               console.log(response.data) /// data present
               return response.data
          } catch (error) {
               console.log(error)
          }
     }
)

export const authSlice = createSlice({
     name: 'auth',
     initialState: { user: {}, status: '', message: '', success: false, error: '' },
     reducers: {
          [login.pending]: (state, action) => (
               state.status = 'loading'
          ),
          [login.fulfilled]: (state, { payload }) => {
               state.user = payload.user
               state.status = 'success'
               state.message = payload.message
               state.success = true
               state.error = ''
          },
          [login.fulfilled]: (state, { payload }) => {
               state.user = payload
               state.status = 'failed'
               state.success = false
               state.error = payload
          }
     }
})

Observable emits no value

I am new to Observables. I am using a switchMap to loop through an array of Observables from firestore, retriving two streams, combining the outputs of the streams into a new Observable Array.

createSuperPolicy( product:VehicleProducts, vehicle:Vehicle, id:String, policyCertID:String) : Observable<SuperVehiclePolicy>{

    var temp = new SuperVehiclePolicy;
   
    
      temp.policyID =  id,
      temp.vendor =  product.vendor,
      temp.title  = product.title,
      temp.premium = product.premium,
      temp.offer = product.offer,
      temp.reg = vehicle.registrationNumber ,
      temp.benefits = product.Benefits,
      temp.policyCertID =  policyCertID 

      
     

    return  temp as unknown as Observable<SuperVehiclePolicy>
  }

  populateVehiclePolicyList = this.vehiclePolicyService.getPolicies().pipe(
       switchMap((policies:VehiclePolicy[]) => {
         var policyList$: Observable<SuperVehiclePolicy>[] = [];
         policies.forEach(policy => {
          var product$: Observable<VehicleProducts> = this.vehicleProductService.getProductByID(policy.vehicleProductID)          
          var vehicle$: Observable<Vehicle> = this.vehicleService.getVehicleByID(policy.vehicleID)
          var id$ = of(policy.id)
          var certID$ = of(policy.policyCertID)

          combineLatest(product$, vehicle$, id$,certID$)
          .pipe(map(([product, vehicle, pid,certID]) => this.createSuperPolicy(product,vehicle, pid, certID)))
          .subscribe((val) => policyList$.push(val));     
         });
         
         console.log(policyList$)
         return forkJoin(policyList$);     
       })
     )

Calling viewing the contents of the new Array of Observables(policyList$) displays the contents of the array.

Now when I subscribe to populateVehiclePolicyList, as below,


this.displayService.populateVehiclePolicyList.subscribe(((policy: SuperVehiclePolicy[]) => {console.log(policy)}))

Console.log(policy) returns neither a value nor an error.
I am confused as to what is happening.
How can I successfully subscribe to populateVehiclePolicyList, so as to consume the output?

How to organize the correct application architecture VUE3 Composition API?

I have a Homepage in which there is a Header component in which there is a button calling a modal window, a modal window is a regular UI element with basic settings, to which I need to pass HTML with, for example, registration, but I don’t quite understand how to do it correctly while storing the state without Vuex. At the moment it looks like this:

controllers
 |--ModalsController.js // here I planned to store the state of the modal window (open/closed/switched)
ui
 |--Heaader.vue //there is a button calling a specific modal window (for example registration) 
 |--ModalBase.vue //basic layout of the modal window

pages
 |--Homepage.vue <Header/>
 login
   |--Login.vue     // Html of the modal SignIn window
   ...

But after reading the documentation several times, I didn’t figure out how to link it all, I’d really appreciate it if someone could tell me. Thank you in advance!

Cannot click or select span elements, after a canvas is focused in HTML – debugging?

I don’t often work with HTML these days, and I’m working with some JS libraries that manipulate canvas. I got done all that I needed – but I just realized, that

  • When the webpage starts, all text is selectable (titles, subtitles, notifications etc – basically all text in spans and divs)
  • Then, I typically click on the canvas and interact with it
  • But, if after clicking the canvas, I try to go to, say, the title span, and click on it to select – the text is not selectable anymore (and no text on the webpage is anymore, apart from text form inputs)

So, I tried looking into this, and found:

HTML input fields does not get focus when clicked

The root cause of the problem is disableSelection(). It is causing all the problems, but removing it is not a solution, as (at least in 2016 or slightly before), on touch-screen devices, you “have” to use this if you want to be able to move objects with jQuery.

So, disableSelection is apparently jQuery, but so far I have just used vanilla javascript in my project (I think, but some of the libraries I use might use jQuery).

Anyways, I thought – before I try to blindly copy/paste online code, in an attempt to restore selectability, – could I somehow confirm through the DOM inspector in the browser, that an element is selectable or not? Say, here is how my Firefox Inspector form Web Developer Tools looks like:

enter image description here

Is there something accessible in the Inspector, like a CSS property, to tell me if an object is selectable? If not, can I quickly run a JavaScript one-liner in the browser Console, and find out the selectability status of an element?

float number divided float number expect wrong number

My problem is a wrong result.
I have a function this function has a distance and a time.
The result I want to achieve is calculating running speed.

function runningPace(distance, time) {
  let result = time.replace(":", ".")
  let fl = parseFloat(result)
  let calc = fl / distance
  let num = calc.toFixed(2) + ''
  if(num.length === 1) {
    num = num + '.00'
  }
  let rep = num.replace('.', ':')
  console.log(distance, time, result, fl, calc, rep, num)
  
  return rep;
}

console.log(runningPace(5, '25:00'))
console.log(runningPace(4.99, '22:32'))

I wrote such a function. Sorry for the naming, I’ll fix it when I get it fixed.

When I test this code, the output is:

expected ‘4:47’ to equal ‘4:30’

‘4:30’ => four minute thirty second

How can I find a solution? Thanks everyone in advance.

Performance advice on calculating rows/columns based on window-resize for a layout grid (virtualization)

Given you have a row width variable of a container, and items populated inside of it, calculating rows/columns based on that within useEffect hooks seems very expensive.

Looking for advice, conceptually on making it more performant.

Say you’re measuring variables of row width (container width), item height and item width.

Calculating the amount of columns that would fit in the container would be Math.floor(rowWidth / itemWidth)

Calculating the column width + the appropriate gap

columnWidth = itemWidth + (rowWidth - (itemWidth * columns)) / columns

Then the row height would be

itemHeight + 100px (any variable)

Now most of this logic, on window-resize would have to be inside of a useEffect so it keeps changing, but like I said, it all feels very expensive. So just curious on how to do it better.

Thank you!

How to return a react component with the for in statement?

I’m trying to iterate over a nested object with the for..in statement an return text component for each object iterated over.

const animals = {
  "cat": Object {
    "number": 0,
  },
  "dog": Object {
    "number": 1,
  }
{ 
      for(let item in animals) {
        for(let property in animals[item]){
          return (
            <Text>{item}</Text>
            <Text>{animals[item][property]}</Text>
          )
      }
    }
}

As you see above, I tried to wrap the function in curly brackets in hopes of using jsx to render the components much like one would do with .map, but I got a slew of errors, so I’m pretty sure this incorrect.

My Linter says Expression expected for the two for(s) and the return ().

I can console.log item, and animals[item][property] so I am confident everything outside the return () is correct.

How would I go about correctly returning the Text elements?

How can I detect if a serviceworker install fails?

My serviceworker is partially generated by gulp, so there’s some chance it ends up with a SyntaxError or TypeError if I’ve made a mistake, and I’d like to be about to detect in my navigator.serviceWorker.register code that this has occurred, and send an error report.

I haven’t figured out how to do this. I figured there’d be some sort of “on fail” event but I haven’t found one. It looks like maybe I’m looking for an SW with a redundant state…

I tried

const newWorker = reg.installing
newWorker.addEventListener('statechange', () => {
  if (newWorker.state == 'redundant') {
    // log error
  }
})

but the condition doesn’t seem to fire. This condition also doesn’t fire:

reg.addEventListener('updatefound', () => {
  if (reg.redundant) {
    // log error
  }
})

I don’t see any examples in the SW tutorials of this, which is surprising since it seems like a sort of basic thing to want to notice and detect.

React paint flash in a simple example (comparison)

In a simple react app (create-next-app) with two counters, ‘paint flash’ utility in Chrome shows a lot of repainting.

function Counter() {
const [val, setVal] = useState(0);

  return (<>
    <p>{val}</p>
    <button onClick={() => { setVal(val + 1) }}>increment</button>
    <button onClick={() => { setVal(val - 1) }}>decrement</button>
  </>)
}

function App() {
  return <>
    <Counter />
    <Counter />
  </>
}

enter image description here

On the other hand, DOM manipulation with JS achieves minimum repaints.

<p id="val0"></p>
<button id="inc0">increment</button>
<button id="dec0">decrement</button>

<p id="val1"></p>
<button id="inc1">increment</button>
<button id="dec1">decrement</button>

<script>
    let v0 = 0;
    let v1 = 0;

    let val0 = document.getElementById("val0")
    let val1 = document.getElementById("val1")
    let inc0 = document.getElementById("inc0")
    let inc1 = document.getElementById("inc1")
    let dec0 = document.getElementById("dec0")
    let dec1 = document.getElementById("dec1")

    val0.innerText = v0;
    val1.innerText = v1;

    inc0.onclick = () => {val0.innerText = ++v0;}
    inc1.onclick = () => {val1.innerText = ++v1;}

    dec0.onclick = () => {val0.innerText = --v0;}
    dec1.onclick = () => {val1.innerText = --v1;}

</script>

export default App

enter image description here

Is there something I can do to remove the repaints or is this React’s core inefficiency? Also, is my intuition to trust Chrome’s ‘paint flash’ more than ‘React dev tools’ correct?

ckeditor5 using the downcastwriter and the upcastwriter to wrap comments

I’m looking to get ckeditor5 to wrap comments around its own tag rather than a p.

In the source view i’m inputting:

<p>
Some text.
</p>
// Here we have some comments
<p>
Some text 2.
</p>

It becomes

<p>
Some text.
</p>
<p>// Here we have some comments</p>
<p>
Some text 2.
</p>

But I want:

<p>
Some text.
</p>
<comment>// Here we have some comments</comment>
<p>
Some text 2.
</p>

Instead.

And upon downcasting it should become the initial version.

How can I do this by customizing upcast and downcast?