Empty Div Preventing Interaction with amCharts5 MapChart on Vue3 - frontend

I decided to dip my toes in Vue and have had an idea for a website for a while which I'd like to use amCharts5 for.
I had some issues initially as all the info I could find was related to Vue2, but I think I've somewhat wrapped my head around Vue3 and its composition API.
The MapChart is created, however there is always a div slapped on top of it which prevent any interaction. If I delete this element via DevTools, the MapChart becomes interactive.
I've tried debugging this and commenting sections of the code out, regardless this div is always created. And I simply can't figure out if it's injected by Vue or if amCharts 5 is the culprit.
The highlighted element is the one I must delete for it to become interactive.
Here's how the component is setup;
<template>
<div class="testClass" ref="chartdiv">
</div>
</template>
<script setup lang="ts">
import * as am5 from "#amcharts/amcharts5";
import * as am5map from "#amcharts/amcharts5/map";
import am5geodata_worldLow from "#amcharts/amcharts5-geodata/worldLow";
import am5themes_Animated from '#amcharts/amcharts5/themes/Animated';
import { ref, onMounted, onUnmounted } from "vue";
const chartdiv = ref<HTMLElement | null>()
var root!: am5.Root;
onMounted(() => {
if (chartdiv.value) {
// Create the Root
var root = am5.Root.new(chartdiv.value);
// Setup the MapChart
var chart = root.container.children.push(
am5map.MapChart.new(root, {
panX: "rotateX",
panY: "rotateY",
projection: am5map.geoOrthographic(),
centerMapOnZoomOut: false
})
);
// Setup Animations
root.setThemes([
am5themes_Animated.new(root)
]);
// Create MapPolygons
var polygonSeries = chart.series.push(
am5map.MapPolygonSeries.new(root, {
geoJSON: am5geodata_worldLow
})
);
// Setup MapPolygon Styling
polygonSeries.mapPolygons.template.setAll({
tooltipText: "{name}",
fill: am5.color("#909090")
});
// Setup MapPolygon Hover Styling
polygonSeries.mapPolygons.template.states.create("hover", {
fill: am5.color("#FF0000"),
stroke: am5.color("#00FF00"),
strokeWidth: 2
});
polygonSeries.mapPolygons.template.events.on("click", function(event) {
//console.log("Clicked: {0}", event.target);
});
// Setup Background
var backgroundSeries = chart.series.unshift(
am5map.MapPolygonSeries.new(root, {})
);
backgroundSeries.mapPolygons.template.setAll({
fill: am5.color(0x2c84d0),
stroke: am5.color(0x2c84d0)
});
backgroundSeries.data.push({
geometry: am5map.getGeoRectangle(90, 180, -90, -180)
});
}
});
onUnmounted(() => {
if (root) {
root.dispose();
}
});
</script>
<style scoped>
.testClass {
width: 50vw;
height: 50vh;
}
</style>

When you create a Vite-powered Vue project, it automatically creates a bunch of CSS files for you. One of those is base.css.
Inside this file, you'll find these lines which causes all the headache;
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
position: relative;
font-weight: normal;
}
Removing those lines will fix the issue.

Related

How to Inject CSS changes into my Electron js app?

I use loadURL to load the web, I want to make some changes. Is there a way to inject a css snippet once the page is rendered?
There are extensions for chrome that do what I want (like UserCSS), but I understand that they can't be used inside an Electron App.
After your page has completed loading...
Here is an example of adding CSS:
// When document has loaded, initialize
document.onreadystatechange = (event) => {
if (document.readyState == "complete") {
// Document has finished loading here
var styles = `img#license {
animation: none;
animation-iteration-count: 1;
animation-fill-mode: forwards;
position: absolute;
z-index: 3;
width: 375px;
top: 204px;
left: 112px;
visibility: hidden;
}`
var styleSheet = document.createElement("style");
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);
}
};
I use the above to display a unlicensed image over my Electron app from the preload.js script, as it has access to the document element.
Edit the CSS to your needs.

Cytoscape Cola Layout: How to restart the layout without any change of positions?

I'm trying to use the Cytoscape cola layout to render a graph that should apply a force directed layout while using it (so when dragging nodes around, they should act as if there is some gravity involved).
Relevant libraries:
https://github.com/cytoscape/cytoscape.js
https://github.com/tgdwyer/WebCola
https://github.com/cytoscape/cytoscape.js-cola
My first problem is that adding nodes to the graph via add(node) doesn't include them in the cola layout algorithm. The only way I found around that is to destroy the layout, re-initialize it and start it again. But this causes the nodes to jump in some cases.
I assumed that this was due to the fact that I completely destroyed the old layout but when setting up a minimal example, I realized that even just calling layout.stop() and layout.run() leads to nodes being repositioned.
In the following example, there is only one node. Moving the node via drag and drop, then pressing the "stop" button and then the "start" button causes the node to jump back to its initial position:
document.addEventListener('DOMContentLoaded', function(){
// Register cola layout
cytoscapeCola(cytoscape);
var nodes = [{ data: { id: 1, name: 1 } }]
var edges = [];
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
style: [
{
selector: 'node[name]',
style: {
'content': 'data(name)'
}
},
{
selector: 'edge',
style: {
'curve-style': 'bezier',
'target-arrow-shape': 'triangle'
}
},
],
elements: {
nodes: nodes,
edges: edges
}
});
var layout = cy.layout({
name: 'cola',
infinite: true,
fit: false,
});
layout.run();
document.querySelector('#start').addEventListener('click', function() {
layout.run();
});
document.querySelector('#stop').addEventListener('click', function() {
layout.stop();
});
document.querySelector('#add-node').addEventListener('click', function() {
var id = Math.random();
cy.add({ group: 'nodes', data: { id: id, name: id } });
cy.add({ group: 'edges', data: { source: id, target: _.head(nodes).data.id } });
layout.stop();
layout.destroy();
layout = cy.layout({
name: 'cola',
infinite: true,
fit: false,
});
layout.run();
});
});
body {
font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
font-size: 14px;
}
#cy {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
z-index: 999;
}
h1 {
opacity: 0.5;
font-size: 1em;
font-weight: bold;
}
#buttons {
position: absolute;
right: 0;
bottom: 0;
z-index: 99999;
}
<!DOCTYPE>
<html>
<head>
<title>cytoscape-edgehandles.js demo for infinite layout</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
<script src="https://unpkg.com/webcola/WebCola/cola.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cytoscape-cola#2.4.0/cytoscape-cola.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
<script src="cytoscape-edgehandles.js"></script>
</head>
<body>
<h1>cytoscape-edgehandles demo with an infinite layout</h1>
<div id="cy"></div>
<div id="buttons">
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="add-node">Add Node</button>
</div>
</body>
</html>
Is this a bug or am I doing something wrong? Does anyone know how to stop and restart the layout without the nodes changing their position?
Thanks a lot,
Jesse
Okay actually you were very close #Stephan.
The problem was that WebCola centers the nodes when calling start by default:
https://github.com/tgdwyer/WebCola/blob/78a24fc0dbf0b4eb4a12386db9c09b087633267d/src/layout.ts#L504
The cytoscape wrapper for WebCola does not currently support this option, so I forked it and added the option myself:
https://github.com/deje1011/cytoscape.js-cola/commit/f357b97aba900327e12f97b1530c4df624ff9d61
I'll open a pull request at some point.
Now you can smoothly restart the layout like this:
layout.stop();
layout.destroy(); // cleanup event listeners
layout = graph.layout({ name: 'cola', infinite: true, fit: false, centerGraph: false });
layout.run()
This way, the nodes keep their position 🎉

Vue.js Application - video element denies streaming on mobile

I'm working on a Vue.js web app that needs to support video streaming. The backend is a Node.js app. It's pulling the videos from an S3 bucket and sending an unbuffered stream to the client. Here's the frontend code:
<template>
<div class="page-container">
<div v-if="currentVideo" class="pageContent">
<section-head>{{ currentVideo.name }}</section-head>
<p>{{ currentVideo.description }}</p>
<video
v-if="videoUrl"
:poster="currentVideo.thumbnail"
playsinline
controls
controlslist="nodownload"
class="stream"
type="video/mp4"
:key="videoUrl"
:src="videoUrl"
/>
<section-head>See More</section-head>
<gallery />
</div>
<h1 v-else class="sorry">
If you're seeing this message, you may have accidently gone to the wrong page.
Please go to the <router-link to="/">Home</router-link> page.
</h1>
</div>
</template>
<script>
import sectionHead from '../components/atoms/Header/SectionHead.vue';
import config from '../../config.js';
import gallery from '../components/molecules/Gallery/Gallery.vue';
export default {
name: 'Stream',
components: { sectionHead, gallery },
computed: {
currentVideo() {
return this.$store.state.currentVideo;
},
videoUrl() {
return 'https://' + config.currentEnvAPI() + '/stream/' + this.currentVideo.video;
},
},
};
</script>
<style lang="scss" scoped>
#import '../styles/_variables.scss';
.page-container {
margin: 0 auto;
p {
text-align: center;
font-size: 25px;
margin: 0 0 6px;
}
}
.stream {
display: block;
margin: 0 auto;
width: 750px;
height: auto;
outline: none;
#include tablet {
width: 650px;
}
#include phone {
width: 100%;
}
}
.sorry {
text-align: center;
padding: 120px;
}
</style>
And I'm setting and getting the video object from VueX here:
import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions.js';
import mutations from './mutations.js';
Vue.use(Vuex);
const state = {
videoList: [],
videoObjects: [],
loadingData: false,
currentVideo: null,
currentGallery: [],
};
export default new Vuex.Store({
state,
actions,
mutations,
});
This is the route that I'm calling on the backend:
app.get('/stream/:video', async (req, res) => {
let videoParams = {
Bucket: BUCKET_NAME,
Key: req.params.video,
};
S3.getObject(videoParams)
.on('httpHeaders', function (statusCode, headers) {
res.set('Content-Length', headers['content-length']);
res.set('Content-Type', headers['content-type']);
res.set('Accept-Ranges', headers['accept-ranges']);
this.response.httpResponse.createUnbufferedStream()
.pipe(res);
})
.send();
});
As far as I can tell, this is a good implementation because it works fine on desktop, both locally and deployed. I only have issues on mobile browsers. I've tried both Chrome and Safari on two different iPhones (no access to an Android device). This is all I see for all of my videos:
I also took the time to set up an SSL certificate for all of my endpoints, so I know the videos are streaming over https. I was thinking that the size of the videos (between 250 - 550 MB) may be the issue, but I also noticed that even though the element is disabled, the connection still transfers the whole thing.
I would think if it was a server side issue that it wouldn't send the whole file, but it does. So wouldn't the issue be client side? I can't figure out why it's not working though. The files are mp4 and I'm sure that they should work because I've tried other links to test with mp4 videos and they've worked. I've changed up the element attributes a lot too. I've tried both with and without playsinline, autoplay, and muted. I've tried having the source element as a child of the video element and that still didn't work. I'm also not getting any console errors, so I can't figure out what the actual problem is and I'm not sure how else I can troubleshoot this.
the h.264 profile of your example file in the comments is "high" but ios safari only supports "base". if you open the file directly in safari, it won't play either.
see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW9

How can I set an Overlay on top when I click on it

I have an Openlayers map with a lot of overlays (Point-coordinates).
These overlays are often very close to each other or overlapping.
When I click on an existing Overlay I want the Overlay to be set on top, so that it is fully seen, not behind any other Overlay.
So far I have only seen that the Layers can be set with an z-index. Is it possible to do that with overlays, too?
I would like to do something like that:
map.setLayerIndex(markers, 99);
but with an overlay
Overlays are controls, which are positioned on an coordinate instead of being in a fixed place. They are basically nothing more but regular html div elements and change position with the map.
This also means, you can apply normal CSS styling and use z-index on them.
var layer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [layer],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
// Vienna marker
var marker1 = new ol.Overlay({
position: ol.proj.fromLonLat([16.3725, 48.208889]),
positioning: 'center-center',
element: document.getElementById('marker1'),
stopEvent: false,
className: 'm1 ol ol-overlay-container ol-selectable'
});
map.addOverlay(marker1);
marker2 = new ol.Overlay({
position: ol.proj.fromLonLat([23.3725, 48.208889]),
positioning: 'center-center',
element: document.getElementById('marker2'),
stopEvent: false,
className: 'm2 ol ol-overlay-container ol-selectable'
});
map.addOverlay(marker2);
function clicked(selector) {
console.log('clicked overlay', selector);
document.querySelectorAll(".ol").forEach(function(el){
el.classList.remove('active');
});
document.querySelector(selector).classList.add('active');
}
html, body, .map {
min-height: 50px;
min-width: 50px;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.marker {
width: 30px;
height: 30px;
border: 1px solid #088;
border-radius: 15px;
background-color: #0FF;
}
.m1 .marker {
background-color: #FF0;
}
.active {
z-index: 1234782904789;
}
.active .marker {
background-color: red;
}
<link href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#main/dist/en/v7.0.0/legacy/ol.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#main/dist/en/v7.0.0/legacy/ol.js"></script>
<div id="map" class="map"></div>
<div id="marker1" title="Marker" class="marker" onclick="clicked('.m1')"></div>
<div id="marker2" title="Marker" class="marker" onclick="clicked('.m2')"></div>
The existing answer works, but it doesn't preserve the z-order of the overlays, it only guarantees that the clicked one will be on top. Since it is the only element with a z-index in this stacking context, the z-order of the other elements will be random.
Here is a solution that brings the clicked overlay to the front, while preserving the current z-order of all the other ones:
export function bringToFront (map: PluggableMap, clickedOverlayElement: HTMLElement) {
const overlays = map.getOverlays().sort(zIndexComparator);
overlays.forEach((overlay, i) => {
const element = overlay.get('element');
const container = pointInfo.closest('.ol-overlay-container') as HTMLElement;
container.style.zIndex = element === clickedOverlayElement ? overlays.length.toFixed() : i.toFixed();
});
}
function getOverlayContainer (overlay: Overlay) {
return overlay.get('element').closest('.ol-overlay-container') as HTMLElement;
}
function zIndexComparator (a: Overlay, b: Overlay) {
return (getOverlayContainer(a).style.zIndex > getOverlayContainer(b).style.zIndex)
? 1
: -1;
}
Just call the bringToFront() function when your overlay element is clicked.

Vuex & Websockets

So currently I am working with VueJS 2 and I am very new with it. Now I was getting some help with some other people, but I am still stuck.
Here is what I want to achieve (example - closely linked to what I want):
I have a NodeJS application that listens on WebSockets. The application listens for connections via WebSocket and will take JSON data, with a command and then a data object with any content needed for that command.
The command for example could be login, and the data be username and password. The login function on the NodeJS application will then take this data, do what it needs and then return it back over the socket, whether it was successful or not, and maybe include an ID and some user information for Vuex to pickup and place in it's state, for the front-end of the application to pick up/use.
Currently I am using this boiler plate: https://github.com/SimulatedGREG/electron-vue
Which has served me very well as a learning curve, due to me wanting to use Vue and Vuex to manage my application and then use WebSockets for managing data to and from the data server.
So if you look at the link I sent in app/src/renderer/ (this is where the main code is for vue and vuex).
A friend of mine added the following code for me as an example and I am stuck trying to get it into vuex as actions and mutations. He made it all in one vue component, so I am struggling on how it works with vuex. As I want to be able to access the (example) loginUser action from anywhere in the application (uses routes for multiple pages/views).
So in the MyApp/app/src/renderer/components/LandingPageView.vue
<template>
<div>
<img src="./LandingPageView/assets/logo.png" alt="electron-vue">
<h1>Welcome.</h1>
<current-page></current-page>
<websocket-output></websocket-output>
<versions></versions>
<links></links>
</div>
</template>
<script>
import CurrentPage from './LandingPageView/CurrentPage'
import Links from './LandingPageView/Links'
import Versions from './LandingPageView/Versions'
import WebsocketOutput from './LandingPageView/WebsocketOutput'
export default {
components: {
CurrentPage,
Links,
Versions,
WebsocketOutput
},
name: 'landing-page'
}
</script>
<style scoped>
img {
margin-top: -25px;
width: 450px;
}
</style>
That is the updated file for that, and then below is the code for the MyApp/app/src/renderer/components/LandingPageView/WebsocketOutput.vue
<template>
<div>
<h2>Socket output:</h2>
<p v-text="socket_out"></p>
</div>
</template>
<script>
var ws = require("nodejs-websocket")
export default {
data () {
return {
socket_out: "connecting to the websocket server..."
}
},
mounted () {
const parent = this
var connection = ws.connect("ws://dannysmc.com:9999", {}, function (conn) {})
connection.on("text", function (text) {
console.log('Text received: ' + text)
parent.socket_out = text
})
connection.on("connect", function () {
connection.send('yo')
})
},
created () {
// Set $route values that are not preset during unit testing
if (process.env.NODE_ENV === 'testing') {
this.$route = {
name: 'websocket-output',
path: '/websocket-output'
}
}
}
}
</script>
<style scoped>
code {
background-color: rgba(46, 56, 76, .5);
border-radius: 3px;
color: #fff;
font-weight: bold;
padding: 3px 6px;
margin: 0 3px;
vertical-align: bottom;
}
p {
line-height: 24px;
color: red;
}
</style>
Everything else is just the boiler plate that you see, so if anyone is willing to help me and give me some tips of what to read that explains this or anything else? as I can't find much information on it unfortunately.
I have an electron application that uses Vue and a websocket for information and here is how I set mine up.
I have a store defined that also actually creates and sets up the websocket.
Store.js
const socket = require("socket-library") // Take your pick of socket libs
const mySocket = new socket(...)
mySocket.on("message", message => store.handleMessage(message))
...other handlers...
const store = {
handleMessage(message){
// do things with the message
}
}
export default store
Renderer.js
import store from "./store"
new Vue({
data:{
store
}
})
This exposes my store at the root level of my Vue and allows me to pass data to components, or what have you. The store manages all the incoming information from the websocket.
With you wanting to use Vuex, you could do essentially the same thing, where Vuex would be your store and when messages come in over the socket, you just pass them to Vuex.
mySocket.on("message", msg => vuexStore.dispatch("onSocketMessage", msg))
and set up your Vue and components to work with Vuex as you typically would.

Resources