How Scroll to Component Vuejs

I am working on a Single-Page-Website using the Vue-Cli and i have a Navigation with some Links in. I have registered All my Components from the links in the Navigation-Component and i want to Scroll to the component when the link is clicked. I tried to use the scrollIntoView() method but it didn’t work. Can someone help me please?

here is my template:

            <div><a href="#" @click="scrollToComponent(el)">Infrastrukturen</a></div>
            <div><a href="#" >Gartenbau</a></div>
            <div><a href="#" >Karriere</a></div>
            <div><a href="#" >Kontakt</a></div>
            <div><a href="#">Impressum</a></div>
        </div>

and here is my script:

import Kontakt from './kontakt.vue'
import Karriere from './karriere.vue'
import Gartenbau from './gartenbau.vue'
import Breitband from './breitband.vue'
import About from './about.vue'

export default {
  name: 'Navigation',
  components: {
      Kontakt,
      Karriere,
      Gartenbau,
      Breitband,
      About,

  },
    data:() => {
        return {
            defaultComp: 'About'

    }
  },
  methods:{
      scrollToComponent(el){
        const comp = el;
        if(comp){
            comp.scrollIntoView({
                behavior:"smooth"
            })
        }
    }
 }
}
</script>

how add global scss styles and mixins to preact app

clear project – from doc

npx create preact-cli default ...
npm i node-sass@10 sass

I tried import to index.js:

import "./style/global.scss";
import App from "./components/app";

export default App;

but cant use mixins and var in components styles

SassError: Undefined mixin.
     @include br;
     ^^^^^^^^^^^

but when Im importing scss file into component scss – all works fine

how can I import globally scss file?

hey guys could u plz help me in this code ? the description in inside the code [closed]

this is mu problem which i need to use arrays inside the function
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo

 * /*
 *   Array properites
 *   ----------------
 *   Complete the function to test if an array is empty (has no values in it)
 *
 * @format
 */

function isEmpty(arr) {
  return; // complete this statement
}

/* 
  DO NOT EDIT BELOW THIS LINE
  --------------------------- */
var numbers = [1, 2, 3];
var names = [];

console.log(isEmpty(numbers));
console.log(isEmpty(names));

/* 
  EXPECTED RESULT
  ---------------
  false
  true
*/

How to remove a event in Vue?

On my Vue instance i have this:

async mounted () {
  document.addEventListener('paste', this.onPasteEvent)
},
beforeDestroy () {
  document.removeEventListener('paste', this.onPasteEvent)
},
methods: {
  onPasteEvent () {
    return async (event) => {
      try {
        const items = event.clipboardData.items
        const files = await this.getBase64Files(items)

        this.transferedItems = files
        this.modal = true
      } catch (error) {
        this.$toast.error('Não foi possível detectar um arquivo na área de transferência.')
      }
    }
  },

I’m trying to destroy the “paste” event when the component is destroyed, but this just doesnt work, i know i need to pass the same reference to removeEventListener, but is this not the same reference?

The only way i found to make this work is placing the onPasteEvent method outside the Vue instance as a constant, but that way i don’t have access to this instance, which is important to me, also, i can’t pass anything as arguments, if i try to pass something, looks like my function create a new reference on memory, making unable to destroy it using removeEventListener.

Please, i just don’t understand how to remove a event in Javascript, can someone help me with that example? I already saw a lot of similar questions but no one explains:

  • How to keep the method reference even if it has parameters.
  • How to remove the event working with Vue instances.

How to access iframe within sandboxed iframe

Within a sandboxed iframe with sandbox="allow-scripts", if I dynamically create a new iframe using JS, I am not able to access it and receive the following error:
DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

iframe.contentWindow.document.open();// throws error

Why is the newly generated iframe considered cross origin? And how can I create an iframe that I can access?
I cannot change the outer iframe sandbox properties.

Why might dragging SVG elements via TouchEvent on iPhone iOS be laggy?

I have created a web interface where the user can drag and drop SVG elements on screen. I am struggling with the performance of moving the SVGs via touch events on iPhone iOS using the webkit engine.

Everything is fine on desktop browsers and on Android phones that I could get hold of, but iOS on iPhones shows very bad performance (seems fine on iOS on one iPad that I could get hold of, but it sometimes leaves some traces of the SVG after moving).

There seems to be a delay before the touchstart event kicks in after touching the device and a delay before the touchend event is triggered after releasing the touch: An audio sample (already loaded) that is supposed to play after picking up or dropping the element plays with a delay of ~1.5 seconds. The touchmove event seems to be handled smoothly though – no delay with moving the SVG (after touchstart has ended).

I have already checked iOS Delay between touchstart and touchmove? – but the site that’s linked to doesn’t help me. I fail to get the scroll event on any element (window, document, svgElement) – and even if I did, I wouldn’t know how this could help me.

I assumed the the issue might be related to the size of the base64 encoded background image that the SVGs are using, but reduzing that size even dramatically didn’t help.

I read about some 300-350ms delay that iOS might have if there’s no “fast tap” mode set, but a) the delay between touching/releasing the screen and playing the audio is longer than 350ms (rather 1.5 seconds) and b) playing with the touch-action CSS property did not help. (Eliminate 300ms delay on click events in mobile Safari)

I am really not sure if I am doing anything wrong (very well possible!) or if the webkit engine on (iPhone) iOS is simply so bad (compared to e.g. Blink on Android that runs flawlessly) that it cannot handle to render/move SVGs? Testing this is particularly iffy, because Browserstack doesn’t issue TouchEvents properly and I never succeded to hook up the single physical iOS device that I have (a 2015 iPod Touch) to my Linux machine for remote debugging (while it’s very simple for Android on Chromium). I’d really be grateful for hints!

An SVG roughly follows the following pattern (some attributes like viewBox, stroke-width etc. omitted):

<svg>  
  <defs><pattern id="SOME_ID"><img href="data:SOME_BASE64_ENCODED_IMAGE" /></defs>  
  <path fill="url(#SOME_ID)" d="SOME_SIMPLE_PATH"></path>  
  <path d="SOME_OTHER_SIMPLE_PATH"></path>  
</svg>  

The SVGs can be moved by MouseEvent or TouchEvent using the following logic:

// this.svgElement is the DOM element within the class
this.svgElement.addEventListener('touchstart', this.handleMoveStarted, false);  
this.svgElement.addEventListener('mousedown', this.handleMoveStarted, false);  

// Keep track of start position and add move/end listeners
handleMoveStarted(event) {  
  event.preventDefault();  
  event.stopPropagation();  
  
  if (event.type === 'touchstart') {  
    this.moveInitialX = event.touches[0].clientX;  
    this.moveInitialY = event.touches[0].clientY;  
    this.svgElement.addEventListener('touchmove', this.handleMoved, false);
    this.svgElement.addEventListener('touchend', this.handleMoveEnded, false);
  }  
  else {
    // Same principle for event.clientX/Y and MouseEvent
  }
   
  // Callback to play audio here
}

// Compute delta position and update
handleMoved(event) {
  event.preventDefault();
  event.stopPropagation();

  let deltaX = 0;
  let deltaY = 0;

  if (event.type === 'touchmove') {
    deltaX = this.moveInitialX - event.touches[0].clientX;
    deltaY = this.moveInitialY - event.touches[0].clientY;
    this.moveInitialX = event.touches[0].clientX;
    this.moveInitialY = event.touches[0].clientY;
  }
  else {
    // Same principle for event.clientX/Y and MouseEvent
  }

  this.svgElement.style.left = `${parseFloat(this.svgElement.style.left) - deltaX}px`;
  this.svgElement.style.top = `${parseFloat(this.svgElement.style.top) - deltaY}px`;
}

// Used to remove listeners on tochenend/mouseup
handleMoveEnded(event) {
  event.preventDefault();
  event.stopPropagation();

  this.svgElement.removeEventListener('mousemove', this.handleMoved);
  this.svgElement.removeEventListener('touchmove', this.handleMoved);
  this.svgElement.removeEventListener('mouseup', this.handleMoveEnded);
  this.svgElement.removeEventListener('touchend', this.handleMoveEnded);

  // Callback to play audio here
}

Get page count from openXML word document in NodeJS

I am currently trying to get the page count of a Word document in openXML format and have been able to get to the point of where I have the XML structure of the document in a readable format, but I can’t seem to find where the page count property is. Any guidance would be appreciated.

const fs = require("fs");
const path = require("path");
const axios = require("axios");

let noRepeatDocs = ['somewebsite.com/somedocument.docx'];


const writeTheFile = async (data) => {
  fs.writeFileSync("read_word_doc", data);
};

const unzipTheFile = async (data) => {
  fs.createReadStream(data)
    .pipe(unzipper.Parse())
    .on("entry", function (entry) {
      const fileName = entry.path;
      const type = entry.type;
      const size = entry.vars.uncompressedSize;

        if (fileName === "word/document.xml") {
            entry.pipe(fs.createWriteStream("./output"));
      } else {
        entry.autodrain();
      }
    });
};

const getWordBuffer = async (arr) => {
  for (const wordDocLink of arr) {
    const response = await axios({
      url: wordDocLink,
      method: "GET",
      responseType: "arraybuffer",
    });
    const data = response.data;
    await writeTheFile(data);
    await unzipTheFile("./read_word_doc"); 
  }
};

getWordBuffer(noRepeatDocs);

xterm.js initial height and scroll bar problems

I am using xterm javascript control, and it is not sizing/resizing properly. I have the following HTML, creating two panes via div, left pane for xterm and right pane for a future side bar.

  <div id="panes" class="panes">
    <div id="terminal-pane" class="terminal-pane"></div>
    <div id="sidebar-pane" class="sidebar-pane"></div>
  </div>

With styles

    html, body {
      height: 100%;
      margin: 0;
    }

    div.panes {
      width: 100%;
      height: 100%;
      display: flex;
    }

    div.terminal-pane {
      width: 70%;
      height: 100%;
      overflow: hidden;
    }

    div.sidebar-pane {
      width: 30%;
      height: 100%;
    }

The xterm is created with

  <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
  <script type="text/javascript" src="node_modules/xterm/lib/xterm.js"></script>
  <script type="text/javascript" src="node_modules/xterm-addon-fit/lib/xterm-addon-fit.js"></script>

  <script>
    var fitAddon = new FitAddon.FitAddon();
    var term = new Terminal();
    term.loadAddon(fitAddon);
    term.open(document.getElementById('terminal'));
    fitAddon.fit();
  </script>

At term.open, when I place a breakpoint, I see the initial width is sized to the table cell width, but the height of the terminal is 25 lines fixed. I expected the height to be sized to the table cell height.

Issue 1: can I do something to make term.open create the terminal initially full height?

Next, after fitAddon.fit, the terminal is resized to an integral of the character dimensions. The width might shrink a few pixels if it is not an even multiple of characters, and the height similarly stretches down all the way, minus any pixels that another row will not fit into.

Issue 2: can the term.open create the terminal on integrals of character width/height, or can I calculate and adjust the div before calling term.open?

Issue 3: the fitAddon.fit isn’t positioning the scroll bar properly. The terminal is on top of it and the left side of the scroll bar can get covered. Is there a way to fix this?

Finally, I add this:

  <script>
    function onSize() {
      if (fitAddon !== undefined) {
        fitAddon.fit();
      }
    }
    window.addEventListener('resize', onSize, false);
  </script>

I should see fitAddon.fit resize the terminal when the browser is resized.

Issue 4: If the width changes but the row count does not, the scroll bar does not move. When sizing bigger, the terminal will cover it, and when sizing smaller, the scroll bar will be clipped. When sizing to its initial position, part or all of the scroll bar shows up. However, if the terminal contains enough lines to scroll, the scroll bar will move with resize.

What should I be doing differently?

Jest – How To Test a Fetch() Call That Returns A Rejected Promise?

I have the following function that uses fetch() to make an API call:

export async function fetchCars(dealershipId) {
  return request('path/to/endpoint/' + dealershipId)
    .then((response) => {
      if (response.ok === false) {
        return Promise.reject();
      }
      return response.json();
    })
    .then((cars) => {
      return parseMyCars(cars);
    });
}

I want to test when the call fails (specifically when return Promise.reject() is returned). I have the following Jest test right now:

(fetch as jest.Mock).mockImplementation(() =>
    Promise.resolve({ ok: false })
);
const result = await fetchCars(1);
expect(request).toHaveBeenCalledWith('/path/to/endpoint/1');
expect(result).toEqual(Promise.reject());

but I get a Failed: undefined message when running the test. I’ve tried using:

(fetch as jest.Mock).mockRejectedValue(() =>
  Promise.resolve({ ok: false })
);

but get a similar Failed: [Function anonymous] message.

What’s the proper way to test for the rejected promise here?

p-multiSelect onchange prevent adding elements with the same index

I have multiselect option with 6 options from array. one of the option is a bit diffrent then the others(it lets adding remark and in the others not). when I am selecting this option and one of the fields x(the remark), after I removing it and selecting again but the field will be null (lets say in the first case I am adding reark and in the second time I’m not) so the multi select will add it twice! but I want 1 velue for every index(without care of the other fields).how should I do it? another place it different in getting the selected values from the server, when it should be selected after the user choosed it it seemes like he didn’t choose.

  <p-multiSelect *ngIf="_decision.decisionStatusId == eDecisionType.Reject || _decision.decisionStatusId == eDecisionType.ReturnedToUser" [required]="formGroup.hasError('remark-reasons-required')"
                   [options]="reasons" defaultLabel="" formControlName="remarks" [(ngModel)]="selectedReasons" optionLabel="hebName"
                   [ngClass]="_decision.decisionStatusId == eDecisionType.ReturnedToUser || _decision.decisionStatusId == eDecisionType.Reject ? '' : 'display-none'"
                   selectedItemsLabel="{0} "
                   (onChange)="onChangeReasonsValue($event)"></p-multiSelect>

.ts

onChangeReasonsValue(event: { value: ReviewDecisionReasonModel[] }): void {
    this.selectedReasons = event.value;
    this._decision.reasons = event.value;
    this.formGroup.markAsDirty();
    this.formGroup.markAsTouched();
    this.formGroup.updateValueAndValidity();
  }

same index values

Trying to convert Stacked BarPlot from D3 to Aframe

As the title suggests, I am trying to convert a Stacked BarPlot from D3 (version 4) to Aframe (using the AR.js library).

The D3 example I am using can be found here:

https://www.d3-graph-gallery.com/graph/barplot_stacked_basicWide.html

When I run the code in the browser, I can see 4 boxes (squares), stacked on top of the other corresponding boxes, however in a weird, layered fashion. I believe this is due to my ‘scale’ and ‘position’ attributes which are incorrectly reading in the data and rendering like they should. Or perhaps it’s how I appended the “a-entity” and then “a-box” to my “a-scene”. Or perhaps it’s neither / both (?)

Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src='https://aframe.io/releases/0.9.2/aframe.min.js'></script>
<script src="https://raw.githack.com/jeromeetienne/AR.js/master/aframe/build/aframe- 
ar.min.js"></script>
<script src="https://raw.githack.com/donmccurdy/aframe-extras/master/dist/aframe- 
extras.loaders.min.js"></script>
<script>
THREEx.ArToolkitContext.baseURL = 
'https://raw.githack.com/jeromeetienne/ar.js/master/three.js/'
</script>
<script src="https://unpkg.com/[email protected]/dist/aframe- 
animation-component.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/aframe- 
randomizer-components.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/aframe- 
entity-generator-component.min.js"></script>
<script src="https://rawgit.com/mayognaise/aframe-mouse-cursor- 
component/master/dist/aframe-mouse-cursor-component.min.js"></script>
</head>

<body style="margin : 0px; overflow: hidden;">

<div id="data_by_age"></div>

<a-scene vr-mode-ui="enabled: false" embedded arjs='sourceType: webcam; 
sourceWidth:1280; sourceHeight:960; displayWidth: 1280; displayHeight: 960; 
debugUIEnabled: false;'>

<a-entity gps-entity-place="longitude: -73.766327; latitude: 41.032730;">
    <a-cursor fuse="true" color="yellow"></a-cursor>
</a-entity>
    <a-camera gps-camera rotation-reader></a-camera>

</a-scene>

<script type="text/javascript">

byAge();

function byAge() {

var scene = d3.select("a-scene");

d3.csv("../static/sample.csv", function(data) {

var subgroups = data.columns.slice(1)

var groups = d3.map(data, function(d){return(d.group)}).keys()

var color = d3.scaleOrdinal()
.domain(subgroups)
.range(['#011f4b','#03396c','#005b96', '#6497b1', '#b3cde0'])

var stackedData = d3.stack()
.keys(subgroups)
(data)

var data_scle = [];
var data_pos = [];

scene
.append("a-entity")
.selectAll("a-entity")
.data(stackedData)
.enter()
.append('a-entity')
.attr("fill", function(d) { return color(d.key); })
.selectAll("a-box")
.data(function(d) { return d; })
.enter().append("a-box")
.attr('rotation', '0 180 0')

.attr('scale', function (d,i) {
    return d + " " + d + " " + d;
})
// .attr('scale', function (d,i) {
//     var x =  i * 10;
//         var y = d;
//         var z = d;
//     data_scle[i] = {"x": x, "y": y, "z": z};
//     return x+" "+y+" "+z;
// })
.attr('position', function(d,i) {
    var x =  i * 175;
        // var y = 0;
        var y = d;
        var z = -500;
    data_pos[i] = {"x": x, "y": y, "z": z};
    return x+" "+y+" "+z;
  })

})

};

</script>
</body>
</html>

Here is my csv file:

group, stronglyAgree, somewhatAgree, stronglyDisagree, notSureNoOpinion
eighteen, 21, 22, 11, 18, 28
thirtyfive, 33, 29, 11, 5, 22
fortyfive, 36, 23, 9, 8, 24
sixtyfive, 42, 24, 7, 10, 17

I’ve also seen github repos tailored specifically for making stacked bar chart components in Aframe, however I couldn’t seem to get it to work properly.

https://github.com/fran-aguilar/a-framedc/tree/master/src/components/barchartstack

Any help would be immensely appreciated.

How to get the sum of a key of consecutive array object and remove the duplicates?

I have a main array –

const arr = [
    {  description: 'Senior', amount: 50 },
    {  description: 'Senior', amount: 50 },
    {  description: 'Adult', amount: 75 },
    {  description: 'Adult', amount: 35 },
    {  description: 'Infant', amount: 25 },
    {  description: 'Senior', amount: 150 }
]

I want help with an es6 operation which will add the amount based on the key(description) and remove the duplicates.

Result array will somewhat look like –

const newArr = [
        {  description: 'Senior', amount: 120 },
        {  description: 'Adult', amount: 110 },
        {  description: 'Infant', amount: 25 },
        {  description: 'Senior', amount: 150 }
]

I have been using the reduce operator to achieve this using the solution, but that removes the non-consecutive objects as well.

It would be really helpful if someone can help me with some es6 operators to perform the same operation.

de.js replace node icon with svg icon

enter image description here
I want use my custom svg icon instead of the circle.
The svg icon is from online url, so, I can use d3.xml to download its content.

        nodes.descendants().forEach(item => {
        const {type, thumb, url} = item.data;
        if ('2d-vector' == type && !thumb) {
            d3.xml(url).then(data => {
                (g.selectAll('.node').node() as any).append(data.documentElement);
                // .attr('x', -15)
                // .attr('y', -15)
                // .attr('width', 30)
                // .attr('height', 30);
            });
            return url;
        }
    });

Above is my tring code, but, I cannot change the svg icon width, heigth.
The original svg icon is very large than the circle.