Refactoring: port ChartJS to Svelte

This commit is contained in:
Pieter Vander Vennet 2025-07-12 14:40:08 +02:00
parent ca4f7566e2
commit 1d48d935ba
7 changed files with 333 additions and 339 deletions

View file

@ -2504,6 +2504,10 @@ input[type="range"].range-lg::-moz-range-thumb {
flex-wrap: wrap-reverse;
}
.place-content-center {
place-content: center;
}
.items-start {
align-items: flex-start;
}

View file

@ -0,0 +1,21 @@
<script lang="ts">
import { onMount } from "svelte"
import { Chart, registerables } from "chart.js"
import type { ChartConfiguration } from "chart.js"
Chart?.register(...(registerables ?? []))
export let config: ChartConfiguration<TType, TData, TLabel>
let canvas: HTMLCanvasElement
onMount(() => {
if (canvas) {
new Chart(canvas, config)
}
})
</script>
{#if config}
<canvas bind:this={canvas} />
{:else}
<slot name="empty" />
{/if}

View file

@ -1,66 +0,0 @@
import BaseUIElement from "../BaseUIElement"
import { Chart, ChartConfiguration, ChartType, DefaultDataPoint, registerables } from "chart.js"
Chart?.register(...(registerables ?? []))
export class ChartJsColours {
public static readonly unknownColor = "rgba(128, 128, 128, 0.2)"
public static readonly unknownBorderColor = "rgba(128, 128, 128, 0.2)"
public static readonly otherColor = "rgba(128, 128, 128, 0.2)"
public static readonly otherBorderColor = "rgba(128, 128, 255)"
public static readonly notApplicableColor = "#fff" // "rgba(128, 128, 128, 0.2)"
public static readonly notApplicableBorderColor = "rgb(241,132,132)"
public static readonly backgroundColors = [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)",
]
public static readonly borderColors = [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
]
}
export default class ChartJs<
TType extends ChartType = ChartType,
TData = DefaultDataPoint<TType>,
TLabel = unknown
> extends BaseUIElement {
private readonly _config: ChartConfiguration<TType, TData, TLabel>
constructor(config: ChartConfiguration<TType, TData, TLabel>) {
super()
this._config = config
}
protected InnerConstructElement(): HTMLElement {
const canvas = document.createElement("canvas")
// A bit exceptional: we apply the styles before giving them to 'chartJS'
if (this.style !== undefined) {
canvas.style.cssText = this.style
}
if (this.clss?.size > 0) {
try {
canvas.classList.add(...Array.from(this.clss))
} catch (e) {
console.error(
"Invalid class name detected in:",
Array.from(this.clss).join(" "),
"\nErr msg is ",
e
)
}
}
new Chart(canvas, this._config)
return canvas
}
}

View file

@ -1,163 +1,59 @@
import ChartJs, { ChartJsColours } from "../Base/ChartJs"
import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig"
import { ChartConfiguration } from "chart.js"
import Combine from "../Base/Combine"
import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig"
import { TagUtils } from "../../Logic/Tags/TagUtils"
import { Utils } from "../../Utils"
import { OsmFeature } from "../../Models/OsmFeature"
import { Utils } from "../../Utils"
export class ChartJsColours {
public static readonly unknownColor = "rgba(128, 128, 128, 0.2)"
public static readonly unknownBorderColor = "rgba(128, 128, 128, 0.2)"
public static readonly otherColor = "rgba(128, 128, 128, 0.2)"
public static readonly otherBorderColor = "rgba(128, 128, 255)"
public static readonly notApplicableColor = "#fff" // "rgba(128, 128, 128, 0.2)"
public static readonly notApplicableBorderColor = "rgb(241,132,132)"
public static readonly backgroundColors = [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)",
]
public static readonly borderColors = [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)",
]
}
export interface TagRenderingChartOptions {
groupToOtherCutoff?: 3 | number
sort?: boolean
hideUnkown?: boolean
hideNotApplicable?: boolean
hideNotApplicable?: boolean,
chartType?: "pie" | "bar" | "doughnut"
}
export class ChartJsUtils {
export class StackedRenderingChart extends ChartJs {
constructor(
tr: TagRenderingConfig,
features: (OsmFeature & { properties: { date: string } })[],
options?: {
period: "day" | "month"
groupToOtherCutoff?: 3 | number
// If given, take the sum of these fields to get the feature weight
sumFields?: ReadonlyArray<string>
hideUnknown?: boolean
hideNotApplicable?: boolean
}
) {
const { labels, data } = TagRenderingChart.extractDataAndLabels(tr, features, {
sort: true,
groupToOtherCutoff: options?.groupToOtherCutoff,
hideNotApplicable: options?.hideNotApplicable,
hideUnkown: options?.hideUnknown,
})
if (labels === undefined || data === undefined) {
console.error(
"Could not extract data and labels for ",
tr,
" with features",
features,
": no labels or no data"
)
throw "No labels or data given..."
}
for (let i = labels.length; i >= 0; i--) {
if (data[i]?.length != 0) {
continue
}
data.splice(i, 1)
labels.splice(i, 1)
}
const datasets: {
label: string /*themename*/
data: number[] /*counts per day*/
backgroundColor: string
}[] = []
const allDays = StackedRenderingChart.getAllDays(features)
let trimmedDays = allDays.map((d) => d.substring(0, 10))
if (options?.period === "month") {
trimmedDays = trimmedDays.map((d) => d.substring(0, 7))
}
trimmedDays = Utils.Dedup(trimmedDays)
for (let i = 0; i < labels.length; i++) {
const label = labels[i]
const changesetsForTheme = data[i]
const perDay: Record<string, OsmFeature[]> = {}
for (const changeset of changesetsForTheme) {
const csDate = new Date(changeset.properties.date)
Utils.SetMidnight(csDate)
let str = csDate.toISOString()
str = str.substr(0, 10)
if (options?.period === "month") {
str = str.substr(0, 7)
}
if (perDay[str] === undefined) {
perDay[str] = [changeset]
} else {
perDay[str].push(changeset)
}
}
const countsPerDay: number[] = []
for (let i = 0; i < trimmedDays.length; i++) {
const day = trimmedDays[i]
const featuresForDay = perDay[day]
if (!featuresForDay) {
continue
}
if (options.sumFields !== undefined) {
let sum = 0
for (const featuresForDayElement of featuresForDay) {
const props = featuresForDayElement.properties
for (const key of options.sumFields) {
if (!props[key]) {
continue
}
const v = Number(props[key])
if (isNaN(v)) {
continue
}
sum += v
}
}
countsPerDay[i] = sum
} else {
countsPerDay[i] = featuresForDay?.length ?? 0
}
}
let backgroundColor =
ChartJsColours.borderColors[i % ChartJsColours.borderColors.length]
if (label === "Unknown") {
backgroundColor = ChartJsColours.unknownBorderColor
}
if (label === "Other") {
backgroundColor = ChartJsColours.otherBorderColor
}
datasets.push({
data: countsPerDay,
backgroundColor,
label,
})
}
const perDayData = {
labels: trimmedDays,
datasets,
}
const config = <ChartConfiguration>{
type: "bar",
data: perDayData,
options: {
responsive: true,
legend: {
display: false,
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
},
},
},
}
super(config)
}
public static getAllDays(
/**
* Gets the 'date' out of all features.properties,
* returns a range with all dates from 'earliest' to 'latest' as to get one continuous range
*
* Useful to use as X-axis for chartJS
* @param features
*/
private static getAllDays(
features: (OsmFeature & { properties: { date: string } })[]
): string[] {
let earliest: Date = undefined
let latest: Date = undefined
const allDates = new Set<string>()
features.forEach((value) => {
for (const value of features) {
const d = new Date(value.properties.date)
Utils.SetMidnight(d)
@ -172,7 +68,7 @@ export class StackedRenderingChart extends ChartJs {
latest = d
}
allDates.add(d.toISOString())
})
}
while (earliest < latest) {
earliest.setDate(earliest.getDate() + 1)
@ -182,100 +78,6 @@ export class StackedRenderingChart extends ChartJs {
days.sort()
return days
}
}
export default class TagRenderingChart extends Combine {
/**
* Creates a chart about this tagRendering for the given data
*/
constructor(
features: { properties: Record<string, string> }[],
tagRendering: TagRenderingConfig,
options?: TagRenderingChartOptions & {
chartclasses?: string
chartstyle?: string
chartType?: "pie" | "bar" | "doughnut"
}
) {
if (tagRendering.mappings?.length === 0 && tagRendering.freeform?.key === undefined) {
super([])
this.SetClass("hidden")
return
}
const { labels, data } = TagRenderingChart.extractDataAndLabels(
tagRendering,
features,
options
)
if (labels === undefined || data === undefined) {
super([])
this.SetClass("hidden")
return
}
const borderColor = [
ChartJsColours.unknownBorderColor,
ChartJsColours.otherBorderColor,
ChartJsColours.notApplicableBorderColor,
]
const backgroundColor = [
ChartJsColours.unknownColor,
ChartJsColours.otherColor,
ChartJsColours.notApplicableColor,
]
while (borderColor.length < data.length) {
borderColor.push(...ChartJsColours.borderColors)
backgroundColor.push(...ChartJsColours.backgroundColors)
}
for (let i = data.length; i >= 0; i--) {
if (data[i]?.length === 0) {
labels.splice(i, 1)
data.splice(i, 1)
borderColor.splice(i, 1)
backgroundColor.splice(i, 1)
}
}
let barchartMode = tagRendering.multiAnswer
if (labels.length > 9) {
barchartMode = true
}
const config = <ChartConfiguration>{
type: options.chartType ?? (barchartMode ? "bar" : "pie"),
data: {
labels,
datasets: [
{
data: data.map((l) => l.length),
backgroundColor,
borderColor,
borderWidth: 1,
label: undefined,
},
],
},
options: {
plugins: {
legend: {
display: !barchartMode,
},
},
},
}
const chart = new ChartJs(config).SetClass(options?.chartclasses ?? "w-32 h-32")
if (options.chartstyle !== undefined) {
chart.SetStyle(options.chartstyle)
}
super([chart])
this.SetClass("flex flex-col justify-center h-full")
}
public static extractDataAndLabels<T extends { properties: Record<string, string> }>(
tagRendering: TagRenderingConfig,
@ -375,7 +177,232 @@ export default class TagRenderingChart extends Combine {
}
data.push(...categoryCounts, ...otherData)
labels.push(...(mappings?.map((m) => m.then.txt) ?? []), ...otherLabels)
if(data.length === 0){
return undefined
}
return { labels, data }
}
/**
* Create a configuration for ChartJS.
* This will show a multi-coloured bar chart, where every bar will represent one day and
* every colour represents a certain value for the tagRendering.
*
* Mostly used in the StatisticsGUI
*
* @param tr
* @param features
* @param options
*/
static createPerDayConfigForTagRendering(
tr: TagRenderingConfig,
features: (OsmFeature & { properties: { date: string } })[],
options?: {
period: "day" | "month"
groupToOtherCutoff?: 3 | number
// If given, take the sum of these fields to get the feature weight
sumFields?: ReadonlyArray<string>
hideUnknown?: boolean
hideNotApplicable?: boolean
}
) {
const { labels, data } = ChartJsUtils.extractDataAndLabels(tr, features, {
sort: true,
groupToOtherCutoff: options?.groupToOtherCutoff,
hideNotApplicable: options?.hideNotApplicable,
hideUnkown: options?.hideUnknown,
})
if (labels === undefined || data === undefined) {
console.error(
"Could not extract data and labels for ",
tr,
" with features",
features,
": no labels or no data"
)
throw "No labels or data given..."
}
for (let i = labels.length; i >= 0; i--) {
if (data[i]?.length != 0) {
continue
}
data.splice(i, 1)
labels.splice(i, 1)
}
const datasets: {
label: string /*themename*/
data: number[] /*counts per day*/
backgroundColor: string
}[] = []
const allDays = ChartJsUtils.getAllDays(features)
let trimmedDays = allDays.map((d) => d.substring(0, 10))
if (options?.period === "month") {
trimmedDays = trimmedDays.map((d) => d.substring(0, 7))
}
trimmedDays = Utils.Dedup(trimmedDays)
for (let i = 0; i < labels.length; i++) {
const label = labels[i]
const changesetsForTheme = data[i]
const perDay: Record<string, OsmFeature[]> = {}
for (const changeset of changesetsForTheme) {
const csDate = new Date(changeset.properties.date)
Utils.SetMidnight(csDate)
let str = csDate.toISOString()
str = str.substr(0, 10)
if (options?.period === "month") {
str = str.substr(0, 7)
}
if (perDay[str] === undefined) {
perDay[str] = [changeset]
} else {
perDay[str].push(changeset)
}
}
const countsPerDay: number[] = []
for (let i = 0; i < trimmedDays.length; i++) {
const day = trimmedDays[i]
const featuresForDay = perDay[day]
if (!featuresForDay) {
continue
}
if (options.sumFields !== undefined) {
let sum = 0
for (const featuresForDayElement of featuresForDay) {
const props = featuresForDayElement.properties
for (const key of options.sumFields) {
if (!props[key]) {
continue
}
const v = Number(props[key])
if (isNaN(v)) {
continue
}
sum += v
}
}
countsPerDay[i] = sum
} else {
countsPerDay[i] = featuresForDay?.length ?? 0
}
}
let backgroundColor =
ChartJsColours.borderColors[i % ChartJsColours.borderColors.length]
if (label === "Unknown") {
backgroundColor = ChartJsColours.unknownBorderColor
}
if (label === "Other") {
backgroundColor = ChartJsColours.otherBorderColor
}
datasets.push({
data: countsPerDay,
backgroundColor,
label,
})
}
const perDayData = {
labels: trimmedDays,
datasets,
}
return <ChartConfiguration>{
type: "bar",
data: perDayData,
options: {
responsive: true,
legend: {
display: false,
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
},
},
},
}
}
/**
* Based on the tagRendering, creates a pie-chart or barchart (if multianswer) configuration for
*
* @returns undefined if not enough parameters
*/
static createConfigForTagRendering<T extends { properties: Record<string, string> }>(tagRendering: TagRenderingConfig, features: T[],
options?: TagRenderingChartOptions){
if (tagRendering.mappings?.length === 0 && tagRendering.freeform?.key === undefined) {
return undefined
}
const { labels, data } = ChartJsUtils.extractDataAndLabels(
tagRendering,
features,
options
)
if (labels === undefined || data === undefined) {
return undefined
}
const borderColor = [
ChartJsColours.unknownBorderColor,
ChartJsColours.otherBorderColor,
ChartJsColours.notApplicableBorderColor,
]
const backgroundColor = [
ChartJsColours.unknownColor,
ChartJsColours.otherColor,
ChartJsColours.notApplicableColor,
]
while (borderColor.length < data.length) {
borderColor.push(...ChartJsColours.borderColors)
backgroundColor.push(...ChartJsColours.backgroundColors)
}
for (let i = data.length; i >= 0; i--) {
if (data[i]?.length === 0) {
labels.splice(i, 1)
data.splice(i, 1)
borderColor.splice(i, 1)
backgroundColor.splice(i, 1)
}
}
let barchartMode = tagRendering.multiAnswer
if (labels.length > 9) {
barchartMode = true
}
const config = <ChartConfiguration>{
type: options?.chartType ?? (barchartMode ? "bar" : "pie"),
data: {
labels,
datasets: [
{
data: data.map((l) => l.length),
backgroundColor,
borderColor,
borderWidth: 1,
label: undefined,
},
],
},
options: {
plugins: {
legend: {
display: !barchartMode,
},
},
},
}
return config
}
}

View file

@ -10,11 +10,11 @@
import Tr from "../Base/Tr.svelte"
import AccordionSingle from "../Flowbite/AccordionSingle.svelte"
import Translations from "../i18n/Translations"
import TagRenderingChart from "../BigComponents/TagRenderingChart"
import ToSvelte from "../Base/ToSvelte.svelte"
import type { TagRenderingConfigJson } from "../../Models/ThemeConfig/Json/TagRenderingConfigJson"
import { Or } from "../../Logic/Tags/Or"
import { Utils } from "../../Utils"
import ChartJs from "../Base/ChartJs.svelte"
import { ChartJsUtils } from "../Base/ChartJsUtils"
export let onlyShowUsername: string[]
export let features: Feature[]
@ -138,13 +138,13 @@
</ul>
{#if diff.tr}
<div class="h-48 w-48">
<ToSvelte
construct={new TagRenderingChart(diff.features, diff.tr, {
<ChartJs config={ChartJsUtils.createConfigForTagRendering(
diff.tr, diff.features,{
groupToOtherCutoff: 0,
chartType: "pie",
sort: true,
})}
/>
}
)} />
</div>
{:else}
Could not create a graph - this item type has no associated question

View file

@ -5,13 +5,14 @@
import LayerConfig from "../../Models/ThemeConfig/LayerConfig"
import Tr from "../Base/Tr.svelte"
import Loading from "../Base/Loading.svelte"
import ToSvelte from "../Base/ToSvelte.svelte"
import TagRenderingChart from "../BigComponents/TagRenderingChart"
import type { Feature } from "geojson"
import { AccordionItem } from "flowbite-svelte"
import ThemeViewState from "../../Models/ThemeViewState"
import DefaultIcon from "../Map/DefaultIcon.svelte"
import { Store } from "../../Logic/UIEventSource"
import ChartJs from "../Base/ChartJs.svelte"
import { ChartJsUtils } from "../Base/ChartJsUtils"
import { Utils } from "../../Utils"
export let layer: LayerConfig
export let state: ThemeViewState
@ -21,6 +22,9 @@
)
let trs = layer.tagRenderings.filter((tr) => tr.question)
let configs = trs.map(tr => ({ tr, config: ChartJsUtils.createConfigForTagRendering(tr, $elements, {
hideNotApplicable: true
}) })).filter(ctr => ctr.config !== undefined)
</script>
<AccordionItem
@ -42,14 +46,22 @@
No features in view
{:else}
<div class="flex w-full flex-wrap gap-x-4 gap-y-4">
{#each trs as tr}
<h3> {#if tr.question}<Tr t={tr.question}/>{:else} {tr.id}{/if}</h3>
<ToSvelte
construct={() =>
new TagRenderingChart($elements, tr, {
chartclasses: "w-full self-center"
}).SetClass(tr.multiAnswer ? "w-128" : "w-96")}
/>
{#each configs as ctr}
<div class="flex flex-col">
<h3>
{#if ctr.tr.question}
<Tr t={ctr.tr.question} />
{:else} {ctr.tr.id}{/if}
</h3>
<div class={ctr.tr.multiAnswer ? "w-96 grow" : "w-60 grow"}>
<ChartJs config={ctr.config }>
<div class="flex place-content-center justify-center items-center w-full h-full" slot="empty">
No data for this entry
</div>
</ChartJs>
</div>
</div>
{/each}
</div>
{/if}

View file

@ -3,9 +3,9 @@
* Shows the statistics for a single item
*/
import TagRenderingConfig from "../../Models/ThemeConfig/TagRenderingConfig"
import ToSvelte from "../Base/ToSvelte.svelte"
import TagRenderingChart, { StackedRenderingChart } from "../BigComponents/TagRenderingChart"
import { ChangesetsOverview } from "./ChangesetsOverview"
import ChartJs from "../Base/ChartJs.svelte"
import { ChartJsUtils } from "../Base/ChartJsUtils"
export let overview: ChangesetsOverview
export let diffInDays: number
@ -22,29 +22,25 @@
{/if}
<h3>By number of changesets</h3>
<div class="flex">
<ToSvelte
construct={new TagRenderingChart(overview._meta, tr, {
<div class="flex w-96 h-96">
<ChartJs config={ChartJsUtils.createConfigForTagRendering(tr, overview._meta, {
groupToOtherCutoff: total > 50 ? 25 : total > 10 ? 3 : 0,
chartstyle: "width: 24rem; height: 24rem",
chartType: "doughnut",
sort: true,
})}
/>
})}/>
</div>
<ToSvelte
construct={new StackedRenderingChart(tr, overview._meta, {
<ChartJs config={ChartJsUtils.createPerDayConfigForTagRendering(
tr, overview._meta, {
period: diffInDays <= 367 ? "day" : "month",
groupToOtherCutoff: total > 50 ? 25 : total > 10 ? 3 : 0,
})}
/>
}
)} />
<h3>By number of modifications</h3>
<ToSvelte
construct={new StackedRenderingChart(tr, overview._meta, {
<ChartJs config={ChartJsUtils.createPerDayConfigForTagRendering(tr, overview._meta, {
period: diffInDays <= 367 ? "day" : "month",
groupToOtherCutoff: total > 50 ? 10 : 0,
sumFields: ChangesetsOverview.valuesToSum,
})}
/>
})}/>