maxm-freshchartsexample.web.val.run
Readme

Deno Fresh Charts Example

Cobbled together from here: https://github.com/denoland/fresh_charts/tree/main/examples

Render charts as HTML or as images. This image is rendered by the val below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/** @jsxImportSource https://esm.sh/react */
import React from "https://esm.sh/react";
// fresh_charts expects React to be available on globalThis/window, not sure why!
globalThis.React = React;
import { Chart, renderChart } from "https://deno.land/x/fresh_charts/mod.ts";
import { ChartColors, transparentize } from "https://deno.land/x/fresh_charts/utils.ts";
import { renderToString } from "npm:react-dom/server";
const chart = () => ({
type: "bar",
options: { devicePixelRatio: 1 },
data: {
labels: months(barCfg),
datasets: [
{
label: "Dataset 1",
data: numbers(barCfg),
backgroundColor: ChartColors.Red,
},
{
label: "Dataset 2",
data: numbers(barCfg),
backgroundColor: ChartColors.Blue,
},
{
label: "Dataset 3",
data: numbers(barCfg),
backgroundColor: ChartColors.Green,
},
],
},
svgClass: "w-full",
});
export default async function(req: Request): Promise<Response> {
if (req.url.endsWith("/img-chart")) {
return renderChart(chart());
}
return new Response(
renderToString(
<>
<Chart {...chart()} />
</>,
),
{ headers: { "content-type": "text/html" } },
);
}
// Utilites to generate random data:
let _seed = Date.now();
const MONTHS = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
export function months({ count = 12, section }: Config = {}) {
const values = [];
for (let i = 0; i < count; ++i) {
const value = MONTHS[Math.ceil(i) % 12];
values.push(value.substring(0, section));
}
return values;
}
export function rand(min = 0, max = 0): number {
_seed = (_seed * 9301 + 49297) % 233280;
return min + (_seed / 233280) * (max - min);
}
interface Config {
min?: number;
max?: number;
from?: number[];
count?: number;
decimals?: number;
continuity?: number;
rmin?: number;
rmax?: number;
prefix?: string;
section?: number;
}
export function numbers({
min = 0,
max = 100,
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
v51
June 3, 2024