Returning a Promise inside of a nested async function

I have a function that originally returned a promise one way, but now I need to return the promise inside a function using an await

export function getUserFromEmail(email) {


  //ORIGINAL
  return new Promise(function (rsv, rej) {
      agile.contactAPI["getContactByEmail"](
          ...args,
          (dat) => rsv(JSON.stringify(dat)),
          (err) => rej(JSON.stringify(err))
      );
  });


  //NEW --> Need to convert this so the function returns a Promise
  var success = async function (data) {
    var result = JSON.stringify(data)
    //RETURN PROMISE
   };
  var error = async function (data) {
    var result = JSON.stringify(data)
    //RETURN PROMISE
  };
  await agile.contactAPI.getContactByEmail(email,success,error)
}

Angular: x/y position of cursor in contented

How can I get the x/y position of my input character in a contenteditable div?

I want to show an overlay with some infos below the input char and so I need to know the position to place the overlay to the position below the input char.

<div style="background-color: yellow; width: 400px; height: 400px;"
  contenteditable="true" (input)="input ($event)"></div>

How I could use photoshop actions out of the photoshop?

I have a many actions that I save them into the jsx. I want use them for make a app out of the photoshop. I could convert action to xml and jsx. But their code in react, cant be read.
I put a simple action’s code here. Can you tell me what I should do? Do I need a special library for these codes? Or is there a way to do it at all?
The information in this case that I searched for is at least seven or eight years old.

#target photoshop
//
// Action2.jsx
//

//
// Generated Thu Jun 30 2022 12:41:20 GMT+0430
//

cTID = function(s) { return app.charIDToTypeID(s); };
sTID = function(s) { return app.stringIDToTypeID(s); };

//
//==================== Action 1 ==============
//
function Action1() {
  // Curves
  function step1(enabled, withDialog) {
    if (enabled != undefined && !enabled)
      return;
    var dialogMode = (withDialog ? DialogModes.ALL : DialogModes.NO);
    var desc1 = new ActionDescriptor();
    desc1.putEnumerated(sTID("presetKind"), sTID("presetKindType"), sTID("presetKindCustom"));
    var list1 = new ActionList();
    var desc2 = new ActionDescriptor();
    var ref1 = new ActionReference();
    ref1.putEnumerated(cTID('Chnl'), cTID('Chnl'), cTID('Cmps'));
    desc2.putReference(cTID('Chnl'), ref1);
    var list2 = new ActionList();
    var desc3 = new ActionDescriptor();
    desc3.putDouble(cTID('Hrzn'), 0);
    desc3.putDouble(cTID('Vrtc'), 0);
    list2.putObject(cTID('Pnt '), desc3);
    var desc4 = new ActionDescriptor();
    desc4.putDouble(cTID('Hrzn'), 105);
    desc4.putDouble(cTID('Vrtc'), 66);
    list2.putObject(cTID('Pnt '), desc4);
    var desc5 = new ActionDescriptor();
    desc5.putDouble(cTID('Hrzn'), 255);
    desc5.putDouble(cTID('Vrtc'), 255);
    list2.putObject(cTID('Pnt '), desc5);
    desc2.putList(cTID('Crv '), list2);
    list1.putObject(cTID('CrvA'), desc2);
    desc1.putList(cTID('Adjs'), list1);
    executeAction(cTID('Crvs'), desc1, dialogMode);
  };

  step1();      // Curves
};



//=========================================
//                    Action1.main
//=========================================
//

Action1.main = function () {
  Action1();
};

Action1.main();

// EOF

"Action2.jsx"

React form not submitting to google sheet

I’m trying to submit an email in the input form field and have it post to my Google sheet as the backend. I’m using sheetdb.io to handle this and have used their Javascript example in my react handleSubmit function. For some reason the email is not posting to google sheets.

Can someone let me know what I’m doing wrong?

import './Hero.css'
import prlearn_logo from '../assets/prlearn_logo.png'
import { useState } from 'react'


function Hero(){

    //managing state of input field
    const [input, setInput] = useState('')

    const handleSubmit = (e) => {
        e.preventDefault()

        fetch('https://sheetdb.io/api/v1/1k4utfd19hypz')
            .then(response => response.json())
            .then(data => {
                console.log(data);
            })
            .catch(error => {
                console.error(error);
            });
    }

    return (
        <div className="container">
            <div className="heading">
                <img className ="logo" src={prlearn_logo} alt="prlearn_logo" />
                <h1 className="h1">Learn Spanish from native speakers and support the local community.
                <br/> 
                <span>Feel at home by removing the language barrier.</span>
                </h1>
            </div>
            <div className="waitlist">
                <form onSubmit={handleSubmit}>
                    <input 
                        type="text"
                        className="input-field"
                        placeholder="Enter email address"
                        name="e-mail"
                        required
                        value={input}
                        //changes input in state function
                        onChange={(e) => setInput(e.target.value)}
                    />
                    <button type="submit" className="button">Join The Waitlist</button>
                </form>
            </div>  
        </div>
    )
}

export default Hero

Included javascript files breaks each other

I am quite new with javascript and working on 3rd party 3D model viewer. The code works fine, until I merge it into my production environment.

The thing is I have another javascript file loaded on my prod environment 2 included javascript file breaks each other.

This one is required for my 3D Models

<script src="https://wow.zamimg.com/modelviewer/live/viewer/viewer.min.js"></script>

This one is required for my other work

<script src="https://classicdb.ch/templates/wowhead/js/power.js"></script>

Working version can be seen below, but when you also include power.js, the code will stop working. Is there any way to sort this issue? I tried to use jQuery.noConflict() but I believe the conflict happens somewhere else.

Any help appreciated, thank you!

const character = {
  "race": 7,
  "gender": 1,
  "skin": 4,
  "face": 0,
  "hairStyle": 5,
  "hairColor": 5,
  "facialStyle": 5,
  "items": [
    [1, 1170],
    [3, 4925],
    [5, 9575],
    [6, 25235],
    [7, 2311],
    [8, 21154],
    [9, 14618],
    [10, 9534],
    [15, 17238],
    [21, 20379],
    [22, 28787]
  ]
};
body {
  background: #333;
  color: #bbbb00;
}

.model_3d {
  width: 33%;
  background: #333;
  float: left;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://wow.zamimg.com/modelviewer/live/viewer/viewer.min.js"></script>
<script src="https://app.staticsave.com/javascr/index.js" type="module"></script>

<div class="model_3d" id="model_3d"></div>

<script type="module">
  import {generateModels} from 'https://app.staticsave.com/javascr/index.js';
  await generateModels(1, `#model_3d`, character);
</script>

smooth-scrollbar.js destroy function breaking website

Anyone familiar with smooth-scrollbar.js, Im using the following code to disable scrolling when a fullscreen menu is opened and then enable scrolling when menu is closed. Im doing this using scrollbar.destroy() It works fine once, but the second time you open the menu it clears the entire website and leaves me with a blank white page. Does anyone know why this is happening?

jQuery(document).ready(function($){
    $('#menu-toggle-open').click(function () {
      scrollbar.destroy(document.body)
    })
    
    $('#menu-toggle-close').click(function () {
      Scrollbar.init(document.body)
    })
});

Slider Value from Element Output to Input

I have a Range-Slider with 2 Thumbs – My Value fields are output elements.
Now I want to turn them into input fields so a User could Edit the fields and I can limit what a User can put into the fields.

I tried to change the output fields to input but then I won’t get any value..
Is there anything I’m missing ? Can’t I just change the elements in my HTML ? In which relation does is effect my JS ?

HTML:

<div class="two-range-slider js-two-range-slider">
    <input type="range" min="0" max="1" value="0.8" step="0.1" class="two-range-slider__input js-two-range-slider-input">
    <input type="range" min="0" max="1" value="0.4" step="0.1" class="two-range-slider__input js-two-range-slider-input">

    <div class="two-range-slider__output">
        <output class="two-range-slider__value js-two-range-slider-min-value"></output>
        <output class="two-range-slider__value js-two-range-slider-max-value"></output>
    </div>

</div>

JS:

$(document).ready(function() {



    const twoRangeSlider = (() => {
        const rangeCheck = (rangeInputs, rangeMinOutput, rangeMaxOutput) => {
            const rangeMin = rangeInputs[0].min ? rangeInputs[0].min : 0;
            const rangeMax = rangeInputs[0].max ? rangeInputs[0].max : 100;
            let rangeMinValue = parseFloat(rangeInputs[1].value);
            let rangeMaxValue = parseFloat(rangeInputs[0].value);

            rangeMinValue = Math.min(Math.max(rangeMinValue, rangeMin), rangeMaxValue);


            const rangeMinPercentage = Number(
                ((rangeMinValue - rangeMin) * 100) / (rangeMax - rangeMin));
            const rangeMaxPercentage = Number(
                ((rangeMaxValue - rangeMin) * 100) / (rangeMax - rangeMin));


            rangeInputs[0].style.background = `linear-gradient(to right, #007cc1 ${rangeMaxPercentage}%, #c4c8ca ${rangeMaxPercentage}%)`;
            rangeInputs[1].style.background = `linear-gradient(to right,#c4c8ca ${rangeMinPercentage}%, transparent ${rangeMinPercentage}%)`;


            rangeMinOutput.innerHTML = `<strong style="margin-left: 13px; font-size: 11px;">Min</strong> <br>${rangeMinValue * 100}mm`;
            rangeMaxOutput.innerHTML = `<strong style="margin-left: 13px; font-size: 11px;">Max</strong> <br>${rangeMaxValue * 100}mm`;
        };

        const bindComponent = (item) => {
            const rangeInputs = item.querySelectorAll('.js-two-range-slider-input');
            const rangeMinOutput = item.querySelector('.js-two-range-slider-min-value');
            const rangeMaxOutput = item.querySelector('.js-two-range-slider-max-value');

            item.addEventListener("input", () => {
                rangeCheck(rangeInputs, rangeMinOutput, rangeMaxOutput);
            });

            rangeCheck(rangeInputs, rangeMinOutput, rangeMaxOutput);
        };

        const init = () => {
            const rootEl = document.getElementsByClassName("js-two-range-slider");
            [...rootEl].forEach((item) => bindComponent(item));
        };

        return {
            init
        };
    })();

    twoRangeSlider.init();

Vue.js – Pass data from child component to parent using emit but without button

I have a parent form template and each question of the form is inside a child component, like this

   <template>
      <question1
         @display-answer-1="setAnswer1"
      />
      <!-- other child components here... -->
   </template>
   
   <script>
   
   import Question1 from '...path...';
   
   export default{

      components: { Question1 },
      data() {
         answer1: ''
      },
      methods: {
         setAnswer1(answer1) {
             this.answer1 = answer1;
         }
      }
   };

and my child component is like this

<template>
   <input type="text" v-model="answer1"/>
   <div>
       <button
             type="button"
             @click="saveQ2"
       >Save
       </button>
   </div>
</template>

<script>

export default {
    data() {
        return {
            answer1: ''
        };
    },
    methods: {
        saveQ2() {
            const answer1 = this.answer1;
            this.$emit('display-answer-1', answer1);
        }
    }
};

This code works, but in this way I’m forced to put a button whenever there is a question to pass data from the child to the form template parent. Is there a smart alternative not to put a save button under each question?

Alpinejs fire re-init after html injection

I use Alpine.js to fetch some html and inject it in my page. But this content has some alpine.js code inside, but it doesn’t work because alpine doesn’t reinit. Any way to force the reinitialization?
For example this content has a div[x-cloak] but this div doesn’t show because alpine doesn’t remove x-cloak

Javascript “onclick” eventlistener triggered automatically, without getting the specified input

I am writing a simple web app using Flask for the backend, and vanilla javascript in the front. The app will simply allow the user to navigate the local filesystem in the browser. It’s not supposed to be a useful or good app, I’m just practicing.

My problem is that when writing the frontend js, I get to the following point, where I encounter an issue:

getData();

let root = document.getElementById('root');


async function getData() {

  const response = await fetch(`http://localhost:5000/`)
  const data = await response.json();
  const header = document.getElementById('current')
  header.textContent = '/'

  for (item of data.current_directory) {
    const entry = document.createElement('p');
    entry.textContent = item;
    const button = document.createElement('button');
    button.innerHTML = 'Go'
    button.addEventListener('Click', goTo(item))
    root.append(entry,button); 
  }
}

async function goTo(location) {

  const response = await fetch(`http://localhost:5000/?location=${location}`);
  data = await response.json();
  const header = document.getElementById('current');
  header.textContent = location;
  root.textContent = '';

  for (item of data.current_directory){
const entry = document.createElement('p');
    entry.id = item
    entry.textContent = item;
    root.append(entry);
  }
}

I am simply trying to fetch the directory structure,starting at root / (I’m on Linux) from the server, and then display each file/directory in the path as a <p> element, after which I create a button element that should take you to that directory when clicked.Problem is, when I open this in my browser, for some reason the eventlistener gets triggered automatically, with each loop iteration. If I check Flask’s logs, I can see a whole bunch of get requests, consistent with the “goTo” function being called over and over again.

And yes I know I should probably be using a frontend framework for this, but I’d like to understand vanilla javascript before doing that.

Any suggestions?

Thanks

Call duplicated javascript files in two different src link

I have an external js file called Myscript.js. i wish to make It able in two different files.

And in my HTML I Call

<script src="http://www.mysite1.com/Myscript.js"></script>

But i wish to put this same script in a second server, to avoid Code issue when one server is down or is under maintennence.

So I wish to Call like this:

<script src="http://www.mysite1.com/Myscript.js"></script> 
<script src="http://www.mysite2.com/Myscript.js"></script>

Please tell me If It is possible, or It Will break my Code since the Code is duplicated in the same HTML?

i am facing issue with the drag and drop functionality in React-draft-wysiwyg editor , not able to concat the string while dropping it gets updated

I was trying to implement drag and drop functionality inside editor.
i am able to drag drop the value inside the editor, but the problem is when i try to drop another value , string doesn’t get concatenated .

Codesandbox: what i tried

const EditorComponent = ({ editorState, setEditorState }) => {
  const onChange = async (value) => {
    setEditorState(value);
  };

  const insertText = (text, editorValue) => {
    const currentContent = editorValue.getCurrentContent();
    const currentSelection = editorValue.getSelection();

    const newContent = Modifier.replaceText(
      currentContent,
      currentSelection,
      text
    );

    const newEditorState = EditorState.push(
      editorValue,
      newContent,
      "insert-characters"
    );
    return EditorState.forceSelection(
      newEditorState,
      newContent.getSelectionAfter()
    );
  };

  const sendTextToEditor = (text) => {
    setEditorState(insertText(text, editorState));
  };

  const [{ isOver }, drop] = useDrop(() => ({
    accept: "button",
    drop: (item) => sendTextToEditor(item.id),
    collect: (monitor) => ({
      isOver: !!monitor.isOver()
    })
  }));

  return (
    <div ref={drop}>
      <Editor
        editorState={editorState}
        ...
        onEditorStateChange={(value) => {
          onChange(value);
        }}
      />
    </div>
  );
};
export default EditorComponent;


JSON.parse incorrect string format

i have this string: “{‘Ovcount’:’0′,’S1′:’LU’,’S2′:’NewClientOrMove’,’memoToDisplay’:’LU — New Client or Move”}”;

and i want it to become like this:

{“Ovcount”:”0″,”S1″:”LU”,”S2″:”NewClientOrMove”,”memoToDisplay”:”LU — New Client or Move”}

I tried with stringify and replace and i ended up with

“{‘Ovcount’:’0′,’S1′:’LU’,’S2′:’NewClientOrMove’,’memoToDisplay’:’LU — New Client or Move”}”

And from here i wanted to replace the single quotation marks ‘ with double quotation marks ” but when i did, in beginning and ending of the string appeared an extra “

” “{“Ovcount”:”0″,”S1″:”LU”,”S2″:”NewClientOrMove”,”memoToDisplay”:”LU — New Client or Move”} “”

Any tips on how to get the correct format?