I've been trying load sigma.js with Svelte / Sveltekit but there seems to be no component integration nor any guidance on how to do this. I tried loading it as client-only code in Sveltekit unsuccessfully but I have no idea if this a legit approach. Is there any working example of a simple graph in Sigma.js running with Sveltekit?
Example for parsing a gexf file:
<script lang="ts">
import Sigma from 'sigma';
import Graph from 'graphology';
import { onMount } from 'svelte';
let container: HTMLElement;
onMount(async () => {
const res = await fetch('/arctic.gexf');
const gexf = await res.text();
const { parse } = await import('graphology-gexf/browser');
const graph = parse(Graph, gexf);
const renderer = new Sigma(graph, container, {
minCameraRatio: 0.1,
maxCameraRatio: 10,
});
})
</script>
<div bind:this={container} class="container" />
<style>
.container {
width: 800px;
height: 600px;
}
</style>
Required packages:
sigma
graphology
graphology-gexf (for reading .gexf files)
graphology-gexf has two modes, one for Node, one for the Browser. To prevent errors in SSR, the browser part can be dynamically imported.
In Svelte you get access to the DOM elements via bind:this instead of querying the DOM, most other things are not that different. Elements bound this way are available in onMount.
arctic.gexf is placed in the static directory. Code is adapted from this example (without all the additional functionality).
I created a simple svelte-sigma app like this:
npm init vite svelte-sigma -- --template svelte
cd my-app
npm install
npm run dev
after I installed sigma.js:
npm install graphology sigma
Now I changed App.svelte like this:
App.svelte
<script>
import Sigma from 'sigma';
import Graph from 'graphology';
import { onMount } from 'svelte';
onMount(() => {
const container1 = document.getElementById("sigma-container");
const graph = new Graph();
graph.addNode("John", { x: 0, y: 10, size: 15, label: "John", color: "blue" });
graph.addNode("Mary", { x: 10, y: 0, size: 10, label: "Mary", color: "green" });
graph.addNode("Thomas", { x: 7, y: 9, size: 20, label: "Thomas", color: "red" });
graph.addNode("Hannah", { x: -7, y: -6, size: 25, label: "Hannah", color: "teal" });
graph.addEdge("John", "Mary");
graph.addEdge("John", "Thomas");
graph.addEdge("John", "Hannah");
graph.addEdge("Hannah", "Thomas");
graph.addEdge("Hannah", "Mary");
const renderer = new Sigma(graph, container1);
});
</script>
<h1> Sigma graph exemple</h1>
<div id="sigma-container" />
<style>
#sigma-container {
width: 550px;
height: 450px;
}
</style>
and I have this render on my localhost:
You can see this exemple
Related
I'm struggling to make uPlot work with svelte. I can't find any minimal working example, so I'm crafting one myself and it does not render. Repro goes as follows:
npm create svelte repro
# y
# skeleton
# yes TypeScript
# yes ESLing
# yes Prettier
# yes Playwright
npm install
npm i uplot
npm run dev -- --open
And then I modify index.svelte to contain the following (best I could come up with, thanks to this answer In SvelteKit, how do you conditionally include a `<script>` block in `app.html`?)
<script lang="ts">
import { browser } from '$app/env';
import { onMount } from 'svelte';
import "uplot/dist/uPlot.min.css"
let uPlot;
function redraw(uPlot) {
if(!uPlot) return;
let data = [new Float32Array([1, 2, 3, 4, 5]), new Float32Array([1, 3, 2, 5, 4])];
const opts = {
width: 600,
height: 300,
scales: {x: {time: false}},
series: [{label: "x"}, {label: "y", stroke: "red"}],
};
new uPlot(opts, data, document.getElementById("uPlot"));
}
onMount(async () => {
if (browser) {
const uplotModule = await import('uplot');
uPlot = uplotModule.default;
console.log("uplot loaded", uplotModule, uPlot);
}
})
$: redraw(uPlot)
</script>
<h1>Welcome to SvelteKit</h1>
<div id="uPlot"></div>
It does not render the plot :( What am I missing?
There are several things to fix or improve:
uPlot does not take typed arrays as data
The reactive statement is a bit pointless, as it only triggers in a meaningful once after uPlot has been loaded
One should not query the DOM in Svelte but use bind:this or events instead
onMount already executes only in the browser
<script lang="ts">
import { onMount } from 'svelte';
import 'uplot/dist/uPlot.min.css';
let plotContainer;
function redraw(uPlot) {
let data = [[1, 2, 3, 4, 5], [1, 3, 2, 5, 4]];
const opts = {
width: 600,
height: 300,
scales: {x: {time: false}},
series: [{label: "x"}, {label: "y", stroke: "red"}],
};
new uPlot(opts, data, plotContainer);
}
onMount(async () => {
const uplotModule = await import('uplot');
const uPlot = uplotModule.default;
redraw(uPlot);
})
</script>
<div bind:this={plotContainer}></div>
REPL equivalent
I installed deck.gl through npm and I'm unable to create layers. At first I was trying to create a google overlay, later I tried it with mapbox overelay. It keeps throwing same error I'm attaching error image and code snippet. I'm using it with angular and I'm trying to create an overlay in my ngOnInit of component.
Thanks!
[![error image][1]][1]
import {ScatterplotLayer} from '#deck.gl/layers';
import {MapboxLayer} from '#deck.gl/mapbox';
//below in my ngOnInit
ngOnInit() {
this.initializeManagers();
this.addListenerForAddressInput();
const myDeckLayer = new MapboxLayer({
id: 'my-scatterplot',
type: ScatterplotLayer,
data: [
{position: [-74.5, 40], size: 100}
],
getPosition: d => d.position,
getRadius: d => d.size,
getColor: [255, 0, 0]
});
}
[1]: https://i.stack.imgur.com/ASRuw.png
Ok so the issue was with npm modules of deck.gl it was using loaders.gl so I installed it but it didn't work so I manually imported script in my index.html and it worked.
<script src="https://unpkg.com/deck.gl#8.7.3/dist.min.js"></script>
<script src="https://unpkg.com/#deck.gl/google-maps#8.7.3/dist.min.js"></script>
I have been trying to use this simple javascript script (https://seatchart.js.org/ or https://github.com/omarmahili/seatchart.js) in my react application. In a html project, one would only add the script and run it, but I struggle with the integration to the React framework. Any approach suggestion would be greatly appreciated.
I have tried some patch work without much success i.e.
Calling the JS function from the script in my react component, but "let sc = new Seatchart(options);", provokes a "'Seatchart' is not defined" error.
Adding "window" in "let sc = new window.Seatchart(options); " results in "Cannot read property 'appendChild' of null" error at "document.getElementById(options.map.id).appendChild(mapContainer)". (may be because the compiler cannot find "document" which is much realted to html and and not much related to React.)
Using UseRef() compiled, but returned a blank screen...
My failling code below omits the entire 1800 lines script which I copied pasted above the React function for "Seatchart()" to be accessed. The script is here
export default function Tickets () {
let options = {
map: {
id: 'map-container',
rows: 9,
columns: 9,
// e.g. Reserved Seat [Row: 1, Col: 2] = 7 * 1 + 2 = 9
reserved: {
seats: [1, 2, 3, 5, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21],
},
disabled: {
seats: [0, 8],
rows: [4],
columns: [4]
}
},
types: [
{ type: "regular", backgroundColor: "#006c80", price: 10, selected: [23, 24] },
{ type: "reduced", backgroundColor: "#287233", price: 7.5, selected: [25, 26] }
],
cart: {
id: 'cart-container',
width: 280,
height: 250,
currency: '£',
},
legend: {
id: 'legend-container',
},
assets: {
path: "../../public",
}
};
let sc = new Seatchart(options);
return (
<div>
<div id="map-container">
</div>
<div id="legend-container">
</div>
<div id="shoppingCart-container">
</div>
</div>
);
}
};
Conceptually, how would I integrate a JS script to my React component?
UPDATE:
In public/index.html:
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<script type="text/javascript" src="../src/containers/SeatChart.js" ></script>
<div id="root"></div>
In SeatChart:
// SeatChart.js script and Option arg. above, but too long to post...
let sc = new Seatchart(options);
localStorage.setItem("scObj", sc);
localStorage.setItem("test", "this is a test");
console.log("You would see this if SeatChart ran successfully);
In Ticket.js
export default function Ticket () {
const sc = localStorage.getItem("scObj");
console.log(sc);
const test = localStorage.getItem("test");
console.log(test)
return (
<div>
<div>Hello from here!</div>
<div id="map-container">
</div>
<div id="legend-container">
</div>
<div id="shoppingCart-container">
</div>
</div>
);
};
Follow below steps:
create a js file in your react application in root, say 'init.js', where you import the required script.
now init.js should have access to let sc = new Seatchart(options)
write your required logic, and return/save/dispatch the result to redux store or local storage. (store.dispatch() can be used.)
2.simply import the aboveenter code here script in your index.html file in your react application.
In your component, read the output from redux/ local-storage as processed by the script function.
I am developing a simple app, where i set a list of consts that i want to use in my development. so i created a file like this:
consts.js
export default {
MAX_HEALTH: 100,
MAX_HEALTH_PERCENTAGE: '100%',
ATTACK_FLAG: 1,
HEALTH_FLAG: -1,
PERCENTAGE: '%',
ATTACK_MIN_RANGE: 1,
ATTACK_YOU_MAX_RANGE: 10,
ATTACK_MONSTER_MAX_RANGE: 7,
SPECIAL_ATTACK_MIN_RANGE: 5,
SPECIAL_ATTACK_YOU_MAX_RANGE:12,
HEAL_MIN_RANGE: 1,
HEAL_MAX_RANGE: 10
}
and i want to access the consts in a separate file on the vue instance:
window.onload = function () {
new Vue({
el: '#appMonster',
data: {
startClicked: false,
monsterLife: {
width: '100%',
life: 100
},
youLife: {
width: '100%',
life: 100
}
},
methods: {
...
for example inside methods, how can i do it?
I already tried to import the file at the top before and after onload, but i always get this error: unexpected identifier, any way to solve this?
I am not using webpack, I am just working with the vue instance accessing the vue script cdn with basic script import.
Thank you
I am not using webpack, I am just working with the vue instance accessing the vue script cdn with basic script import.
If that's the case, don't use import/export. Just:
consts.js:
const constants = {
MAX_HEALTH: 100,
MAX_HEALTH_PERCENTAGE: '100%',
ATTACK_FLAG: 1,
HEALTH_FLAG: -1,
PERCENTAGE: '%',
ATTACK_MIN_RANGE: 1,
ATTACK_YOU_MAX_RANGE: 10,
ATTACK_MONSTER_MAX_RANGE: 7,
SPECIAL_ATTACK_MIN_RANGE: 5,
SPECIAL_ATTACK_YOU_MAX_RANGE:12,
HEAL_MIN_RANGE: 1,
HEAL_MAX_RANGE: 10
}
Other file, provided you imported <script src="consts.js"></script> before, simply do:
// somewhere before: <script src="consts.js"></script>
<script>
window.onload = function () {
new Vue({
el: '#appMonster',
data: {
startClicked: false,
monsterLife: {
width: '100%',
life: constants.MAX_HEALTH // <==== use constants.PROPNAME
},
youLife: {
width: '100%',
life: 100
}
},
methods: {
See plunker demo here.
I am creating an application in node.js utilizing the sails framework. I want to create a report in PDF format. The report needs to contain a chart generated using chart.js. The data is fetched from mongodb and displayed on a canvas. How can I create a PDF file of this chart using node.js?
You can use pdf-creator-node package to create PDF
Following are the steps to create PDF in Node Application
Installation install the pdf creator package by the following command
npm i pdf-creator-node
Add required packages and read HTML template
//Required package
var pdf = require("pdf-creator-node")
var fs = require('fs')
// Read HTML Template
var html = fs.readFileSync('template.html', 'utf8')
Create your HTML Template
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hello world!</title>
</head>
<body>
<h1>User List</h1>
<ul>
{{#each users}}
<li>Name: {{this.name}}</li>
<li>Age: {{this.age}}</li>
<br>
{{/each}}
</ul>
</body>
</html>
Provide Format and Orientation as per your need
"height": "10.5in", // allowed units: mm, cm, in, px
"width": "8in", // allowed units: mm, cm, in, px
or -
"format": "Letter", // allowed units: A3, A4, A5, Legal, Letter, Tabloid
"orientation": "portrait", // portrait or landscape
var options = {
format: "A3",
orientation: "portrait",
border: "10mm"
};
Provide HTML, User data and pdf path for the output
var users = [
{
name:"Shyam",
age:"26"
},
{
name:"Navjot",
age:"26"
},
{
name:"Vitthal",
age:"26"
}
]
var document = {
html: html,
data: {
users: users
},
path: "./output.pdf"
};
After setting all parameters just pass document and options to pdf.create method.
pdf.create(document, options)
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
});
PDFKit.
Installation:
npm install pdfkit
Example:
var PDFDocument = require('pdfkit');
doc = new PDFDocument;
doc.pipe(fs.createWriteStream('output.pdf'));
doc.font('fonts/PalatinoBold.ttf').fontSize(25).text(100, 100);
The simplest way to generate PDFs using NodeJS is to use the pdf-master package.
You can generate static and dynamic PDFs using HTML with one function call.
Installation
npm install pdf-master
Example
Step 1 - Add required packages and generate a PDF
const express = require("express");
const pdfMaster = require("pdf-master");
const app = express();
app.get("", async (req, res) => {
var PDF = await pdfMaster.generatePdf("template.hbs");
res.contentType("application/pdf");
res.status(200).send(PDF);
});
generatePdf() syntax and parameters
generatePdf(
templatePath, //<string>
data, //<object> Pass data to template(optional)
options //<object> PDF format options(optional)
);
Step 2 - Create your HTML Template (save the template with .hbs extension instead of .html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Render dynamic data in template and PDF format options
const express = require("express");
const pdfMaster = require("pdf-master");
const app = express();
app.get("", async (req, res) => {
var students = {
{
id: 1,
name: "Sam",
age: 21
},
{
id: 2,
name: "Jhon",
age: 20
},
{
id: 3,
name: "Jim",
age: 24
}
}
let options = {
displayHeaderFooter: true,
format: "A4",
headerTemplate: `<h3> Header </h3>`,
footerTemplate: `<h3> Copyright 2023 </h3>`,
margin: { top: "80px", bottom: "100px" },
};
let PDF = await pdfMaster.generatePdf("template.hbs", students, options);
res.contentType("application/pdf");
res.status(200).send(PDF);
});
To learn more about pdf-master visit