How do I add a button that would copy displayed text in vue.js?

I’m trying to add a button that would enable me to copy a snippet of code that is in view to the clipboard for a code catalog application in vue.js.

When I use the vue clipboard library and attempt this in the example component:

<div class="full-screen-code-snippet">
  {{ example.codeSnippet }}
</div>

<div class="full-screen-copy-button">
<button v-clipboard:copy="example.codeSnippet"></button>    
</div>

the snippet displays properly but the button does not. What’s going on? How should I go about making this button?

Sending preengagement data to studio flow twilio

In the given below code, Im trying to develop the form using react for webchat of twilio. How to send the data collected from the form to chat window and to studio flow and how to call the component of pendingenagecanvas component. Not able to share the whole file code. If you

handleSubmit(event) {
            event.preventDefault();
           // implement your custom validation logic on your fields
    //     // when validation passes, execute the following
        
  
    
          **      // FlexWebChat.PendingEngagementCanvas.Content.replace(<HeaderColor key="mimize-chat1"   />)
             
                //     FlexWebChat.Actions.invokeAction("StartEngagement", (payload) => { // preEngagementData collected from the form goes here... })
           
    //     });**
               
            }
            }
          validate(){
              let input = this.state.input;
              let errors = {};
              let isValid = true;
              console.log(input,"inputttt")
              if (!input["op"]) {
                isValid = false;
                console.log("inside opppp")
                errors["op"] = "Please enter your dropdownname.";
              }
            
              if (!input["name"]) {
                isValid = false;
                errors["name"] = "Please enter your First name.";
              }
              if (!input["lastname"]) {
                isValid = false;
                errors["lastname"] = "Please enter your Last name.";
              }
          
             
              <input  disabled={this.state.submitDisabled} type="submit" value="Submit" 
          className="btn btn-success" />
        
            </form>
          </div>
        )
      }
    }

Thanks

Some Modules not showing in import suggestion after implementing paths in jsconfig.json

I’m Making My App in Next.js and was struggling thru importing from deep folders

I saw this post https://nextjs.org/docs/advanced-features/module-path-aliases

But after i implemented paths in jsconfig.json

{
  "compilerOptions": {
    "target": "es2020",
    "baseUrl": ".",
    "paths": {
      "@styles/*": ["./styles/*"],
      "@components/*": ["./src/components/*"]
    }
  }
}

I’m not able to see suggestion for import of any other module from node_modules which starts with @

See Here

Because of this i cant use emmets for material ui (mui)

Why pushing a variable containing an array inside another variable, then updating the first also updates the latter?

I was studying JS when faced an unexpected behavior by me. It’s probably something related to local vs global scope, however I could not find the answer. Here how it goes:

I have two arrays, one empty and another with some values. If a push the one with values inside the empty one, then updating the values using .push() method, it will update the array inside the other as well:

let newArr = [];
let valueArr = [0,0];

newArr.push(valueArr); // newArr = [[0,0]]

valueArr.push(0); // newArr = [[0,0,0]] --> updates it

However, if a now try to update the variable using = assignment, it won’t change the array inside newArr

let newArr = [];
let valueArr = [0,0];

newArr.push(valueArr); // newArr = [[0,0]]

valueArr = [0,0,0]; // newArr = [[0,0]] --> does not update it

Does anyone know why pushing has this behavior and reassigning does not? It’s due local/global scope or when I reassign the valueArr variable, the newArr variable loses its track?

How can I store this in localStorage?

I have a login page in react that has a handleSubmit function which looks like this:

const handleSubmit = async e => {
        e.preventDefault();
        console.log(email, password);
        const user = {email, password};
        const response = await axios.get('http://localhost:5000/users');
            let userExists = false;
            console.log(response);
            for (let i = 0; i < response.data.length; i++) {
                console.log(response.data[i].email);
                console.log(response.data[i].password);
                if (response.data[i].email == email && response.data[i].password == password) {
                    userExists = true;
                    if (userExists) {
                        const toAppend = [response.data[i].email, response.data[i].password];
                        console.log(toAppend);
                        localStorage.setItem('user', toAppend);
                        navigate('/');
                        break;
                    };
                };
            };
            if (userExists === false) {
                alert("User does not exist! Did you enter the login data correctly?");
            }
        };

    useEffect(() => {
        const loggedInUser = localStorage.getItem("user");
        if (loggedInUser) {
          const foundUser = JSON.parse(loggedInUser);
          setUser(foundUser);
        }
      }, []);

It gets stored in localStorage and is Key: user, Value:[email protected],test.
However, when I try to access the page again, it should redirect to the homepage (‘/’). Instead, I get an error

react-dom.development.js:22670 Uncaught SyntaxError: Unexpected token e in JSON at position 1
    at JSON.parse (<anonymous>)
    at Login.js:43:1
    at commitHookEffectListMount (react-dom.development.js:22969:1)
    at commitPassiveMountOnFiber (react-dom.development.js:24702:1)
    at commitPassiveMountEffects_complete (react-dom.development.js:24666:1)
    at commitPassiveMountEffects_begin (react-dom.development.js:24653:1)
    at commitPassiveMountEffects (react-dom.development.js:24641:1)
    at flushPassiveEffectsImpl (react-dom.development.js:26848:1)
    at flushPassiveEffects (react-dom.development.js:26801:1)
    at react-dom.development.js:26597:1

I can only assume that I am not storing my data correctly. The response the server returns looks like this when console logged:

{data: Array(2), status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
data: (2) [{…}, {…}]
headers: {content-length: '288', content-type: 'application/json'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: "OK"
[[Prototype]]: Object

I have made the server and it returns

[
    {
        "email": "[email protected]",
        "name": "test",
        "about": null,
        "password": "test",
        "user_id": 1
    },
    {
        "email": "[email protected]",
        "name": "test",
        "about": null,
        "password": "test",
        "user_id": 2
    }
]

when accessed in a browser. I followed this page on how to make this login system.
https://www.freecodecamp.org/news/how-to-persist-a-logged-in-user-in-react/
How can I fix this issue?
Thanks!

slicing array list five elements at a time in javascript

I’m trying to use javascript slice method (please suggest if this is not the right way to use), the array list show five array item at a time and I have created the codepen example to show what I’m trying to do

Let’s assume I have 20 records,
if the user click on first time, I should be getting 1-5 array items
if the user click on second time, I should be getting 5-10 …..so on and so forth.

https://codepen.io/TLJens/pen/NPZyYR

The code here:

    $('#loading').hide();
var counts = 0;
var displayCount = 5;
var starting = 0;
var data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
function slicemydata(sstart, totalsize, eend) {  
    var items = []; debugger;
    if (totalsize <= data.length) {
        if (eend == 0) {
          items = data.slice(sstart,totalsize);
        } else { 
          if (sstart > eend) {
            eend = data.length;
          }
          items = data.slice(sstart, eend);
          sstart =  displayCount + 5;
        }
    }
    console.log(items);
  $('.js-lazy-load-data').append(items);
}

$('.js-lazy-load').click(function () {
 
  counts++;
  slicemydata(starting,data.length,displayCount);
 
    $('.js-lazy-load').fadeOut();
  
    // Minor timeout before showing loader
   // setTimeout(function () {
   //     $('#loading').fadeIn();
   // }, 400); 
  
    // Simulate server call by showing loading gif  
    // for 2.5 seconds before displaying results
    //setTimeout(function () {
    //    $('#loading').fadeOut();
    //}, 2600); 
  
    // Display results after 3 seconds
    setTimeout(function () {
        //$('.js-lazy-load-data').append(data);
        $('.js-lazy-load').show();
    }, 1000);  
});

why do i get [object Promise] [duplicate]

in a request fetch I always find [object Promise]
This is my code:

async function getStartChat() {
        const response = await fetch("lib/start_chat.php")
        let data = await response.text();
        return data;
    }

let saveChat = getStartChat();
if(saveChat !== "") qCHAT.innerHTML = saveChat;

I also tried this other way:

async function getStartChat() {
        const response = await fetch("lib/bot.php").
        then(response => response.text()).
        then(data => { return data }).
        catch(err => console.log(err));
    }

but I always get the same answer

create comment with vue js

I’m trying to create a comment with.post selectId this articles.
i can’t send article and {comment_message:this.comment} together, i have no idea how to fix this.
Do i have to change my function in store or in views methods?
my sql return error sql: “INSERT INTO comments (comment_userId,comment_articleId, comment_message) VALUES (1, ‘1’, NULL)”
If anyone can help, thanks.

store/index.js

createComment: ({ commit }, dataArticles) => {
      return new Promise(() => {
      instance.post(`/comment/${dataArticles.article_id}`)
        .then(function () {
          commit('getComments');
        })
        .catch(function (error) {
          console.log(error)
        });
      })
    },
 createComment(article) {  
      this.$store.dispatch("createComment",article,{comment_message:this.comment});
    },
```

```
<div class="position-comment_send">
                <textarea
                  class="form-control form-control_comment"
                  id="commentText"
                  rows="1"
                  ref="string"
                  v-model="comment"
                ></textarea>
                <button type="submit"
                @click="createComment(article)" 
                class="btn btn-primary">
                  <i class="bi bi-send-fill"></i>
                </button>
              </div>
```

How can I prevent 2 svg paths from being connected?

I am creating some kind of signature field, but I have the following unwanted behavior: when I draw for example 2 lines, at the beginning the second one looks like it is trying to connect to the first one and my question is how can I prevent that?

…in the example below I actually tried to draw 3 lines.

enter image description here

let signature = document.getElementById('signature');
if (signature) {
    let svgpath;
    let params = [];
    signature.onmousedown = function createSvgPath (e) {
        if (e.buttons === 1) {
            svgpath = document.createElementNS("http://www.w3.org/2000/svg", "path");
            svgpath.setAttribute('stroke', 'blue');
            svgpath.setAttribute('stroke-width', '2');
            svgpath.setAttribute('stroke-linecap', 'round');
            svgpath.setAttribute('fill', 'none');
            svgpath.setAttribute('d', `M ${e.offsetX} ${e.offsetY}`);
            signature.append(svgpath);
        }
    };
    signature.onmousemove = function drawSvgPath (e) {
        if (e.buttons === 1) {
            params.push(e.offsetX);
            params.push(e.offsetY);
            if (params.length == 6) {
                let d = svgpath.getAttribute('d');
                svgpath.setAttribute('d', `${d} C ${params[0]} ${params[1]} ${params[2]} ${params[3]} ${params[4]} ${params[5]}`);
                params = [];
            }
        }
    };
}
* {
    font-size: 1rem;
    line-height: 1.5rem;
    font-family: Arial, Helvetica, sans-serif;
    box-sizing: border-box;
}

body { 
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background-color: whitesmoke;
    display: flex;
    justify-content: center;
    align-items: center;
}

#signature {
    display: block;
    width: 800px;
    height: 300px;
    border: none;
    background-color: white;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <svg id="signature"></svg>
</body>
</html>

Honeycomb hexagonal grid?

I’m trying to draw a hexagonal grid in a honeycomb shape.
So far I’m able to draw it in a rectangular shape but I don’t know how to convert my for loop to make a honeycomb shape instead.

This is what I currently have

<html>

<body>
    <canvas width='1080' height='720' id='hexmap'></canvas>
</body>
<script>

    window.addEventListener('DOMContentLoaded', (event) => {

        var canvas = document.getElementById('hexmap');

    var hexHeight,
        hexRadius,
        hexRectangleHeight,
        hexRectangleWidth,
        hexagonAngle = 0.523598776, // 30 degrees in radians
        sideLength = 36,
        boardWidth = 10,
        boardHeight = 10;

    hexHeight = Math.sin(hexagonAngle) * sideLength;
    hexRadius = Math.cos(hexagonAngle) * sideLength;
    hexRectangleHeight = sideLength + 2 * hexHeight;
    hexRectangleWidth = 2 * hexRadius;
    var ctx = canvas.getContext('2d');

        ctx.fillStyle = "#000000";
        ctx.strokeStyle = "#CCCCCC";
        ctx.lineWidth = 1;

    drawBoard(ctx, boardWidth, boardHeight);
    
    function drawBoard(canvasContext, width, height) {

        var i,j;
        //this loop generates a rectangular hexagon grid
        for(i = 0; i < width; ++i) {
            for(j = 0; j < height; ++j) {
                drawHexagon(
                    ctx, 
                    i * hexRectangleWidth + ((j % 2) * hexRadius), 
                    j * (sideLength + hexHeight), 
                    false
                );
            }
        }
    }

    function drawHexagon(canvasContext, x, y, fill) {           
        var fill = fill || false;

        canvasContext.beginPath();
        canvasContext.moveTo(x + hexRadius, y);
        canvasContext.lineTo(x + hexRectangleWidth, y + hexHeight);
        canvasContext.lineTo(x + hexRectangleWidth, y + hexHeight + sideLength);
        canvasContext.lineTo(x + hexRadius, y + hexRectangleHeight);
        canvasContext.lineTo(x, y + sideLength + hexHeight);
        canvasContext.lineTo(x, y + hexHeight);
        canvasContext.closePath();

        if(fill) {
            canvasContext.fill();
        } else {
            canvasContext.stroke();
        }
    }

})
</script>

</html>

Which results in this shape
enter image description here

What I’d like to achieve though is a shape like this
enter image description here

I was able to do it using like 13 separate for loops, shifting the hexagon over manually each time but it wasn’t very practical nor automated.

chair + supertest + promises confusion

I have a function stored in a separate file which has a call to a graphql endpoint.

I am trying to call this function and return an id (which is returned) – however, I am getting an warning that I am using .end and .done

The function:

module.exports = {
    addThing: async function (title, extRef, done) {
        const basicAddCreative = `mutation { ...}`

        let the_id = await request
        .post("/graphql")
        .send({
            query: basicAddCreative
        })
        .set("Accept", "application/json")
        .expect(200)
        .end((err, res) => {
            if (err) return done(err)
            return res.body.data.id
        })
        return the_id
    }
}

And this is called (in a different file)

let cId = helpers.addThing('fnTest', 'fnTest', done)
cId.then(i => console.log(i))

And then when I run this the test I have fails for :
.end() was called twice. This is not supported in superagent
And then I see:
Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises.

Can anyone shed light on how I could fix the above?

Minimize compose window and run function in an Outlook web add-in

I am currently working on a web add-in that processes, modify and then sends the email.

I’m attached to the ItemSend event: <Event Type="ItemSend" FunctionExecution="synchronous" FunctionName="validateBody" />. This validate the body and then sends it.

The problem I have is that processing the email might take up to 40 seconds and I don’t want the user to be blocked for that amount of time.

I was wondering is there a way to minimize the compose window and still run the processing function and the close that minimized window once its done?

I know that the add-in only works on the current item so when I send the email I can still access the other pages but once the email is trying to send itself and close the compose window nothing happens.

This is the function that sends the email:

async function sendInBackGround(htmlArr, message = "") {
const subject = await getEmailSubject();

const messageDiv = "<div>" + message + "</div>";

for (const htmlArrObject of htmlArr) {
    debugger;
    var request = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
    '  <soap:Header><t:RequestServerVersion Version="Exchange2010" /></soap:Header>' +
    '  <soap:Body>' +
    '    <m:CreateItem MessageDisposition="SendOnly">' +
    '      <m:Items>' +
    '        <t:Message>' +
    '          <t:Subject>' + subject.value + '</t:Subject>' +
    '             <t:Body BodyType="HTML"><![CDATA[' + htmlArrObject.html + messageDiv + ']]></t:Body>' +
    '          <t:ToRecipients>' +
    '            <t:Mailbox><t:EmailAddress>' + htmlArrObject.recipient + '</t:EmailAddress></t:Mailbox>' +
    '          </t:ToRecipients>' +
    '        </t:Message>' +
    '      </m:Items>' +
    '    </m:CreateItem>' +
    '  </soap:Body>' +
    '</soap:Envelope>';

    Office.context.mailbox.makeEwsRequestAsync(request, (asyncResult) => {
        console.log(request);
        if (asyncResult.status === "failed") {
            console.log("Action failed with error: " + asyncResult.error.message);
        }
        else {
            console.log("Message sent!");
            mailboxItem.close();
        }
    });
}

}

When I send the item and wait on the compose window for the process to be done, the asyncResult has a status and a value that are defined. But when I change windows while the process is running, for example I go on an other compose window and start writing another email, the asyncResult object has a status of succeeded but the value returned is undefined.

Can someone help?

Nextjs site has favicon in chrome but not in brave

I am developing my first nexjs site. I am setting the favicon in index.js as follows:

      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

Originally I was using a setup where my source files were all in the root directory. I now decided to move them to a src directory. Since then I have observed the following two weird behaviours: 1) The site has a favicon in chrome but not in brave. 2) Even if I comment out the above portion the favicon in chrome remains. The favicon is stored in the public folder which is in the root directory (did not change anything about that) when moving the other files to src.

How do I send fetched data from chrome extension background script to content script?

Once an event is triggered in my content script, it send a message request to the background script and waits for a response.

content.js

chrome.runtime.sendMessage({ userId: userId }, function (response) {
    console.log(response);
});

background.js:

chrome.runtime.onMessage.addListener(function (
  request,
  sender,
  sendResponse
) {
  const userId = request.userId;
  if (userId) {
    fetchData(userId).then((data) => {
      sendResponse({ response: data });
    });
    return true;
  }
});

I’ve tried async/await, moving the “return true” to outside the if statement, but in my content script the response is either undefined (even though fetchData returns the correct data), no response, or the error “the message port closed before a response was received extension”.

The flow I want is:

  1. content.js sends a message request to background.js and waits for a response
  2. background.js receives the message
  3. background.js fetches data via http request
  4. background.js sends resolved promise back to content.js
  5. content.js receives response and logs the data