ozdenui 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/LICENSE +14 -0
- data/NOTICE +5 -0
- data/README.md +242 -0
- data/exe/ozdenui +17 -0
- data/lib/ozdenui/AGENTS.md +210 -0
- data/lib/ozdenui/COMPONENTS.md +3017 -0
- data/lib/ozdenui/app.rb +749 -0
- data/lib/ozdenui/command.rb +107 -0
- data/lib/ozdenui/components.rb +368 -0
- data/lib/ozdenui/dialogs.rb +212 -0
- data/lib/ozdenui/files.rb +124 -0
- data/lib/ozdenui/icon.png +0 -0
- data/lib/ozdenui/kit.json +1 -0
- data/lib/ozdenui/kit.rb +115 -0
- data/lib/ozdenui/look.rb +229 -0
- data/lib/ozdenui/objects.rb +652 -0
- data/lib/ozdenui/server.rb +270 -0
- data/lib/ozdenui/values.rb +273 -0
- data/lib/ozdenui/version.rb +15 -0
- data/lib/ozdenui/web/basic/LICENSE +14 -0
- data/lib/ozdenui/web/basic/basic.min.css +1 -0
- data/lib/ozdenui/web/basic/basic.min.js +78 -0
- data/lib/ozdenui/web/basic/font/open-sans/LICENSE.txt +206 -0
- data/lib/ozdenui/web/basic/font/open-sans/OpenSans-Bold.ttf +0 -0
- data/lib/ozdenui/web/basic/font/open-sans/OpenSans-Regular.ttf +0 -0
- data/lib/ozdenui/web/basic/scroll-bar.min.js +3 -0
- data/lib/ozdenui/web/bridge.js +584 -0
- data/lib/ozdenui/web/comp/accordion.js +659 -0
- data/lib/ozdenui/web/comp/action-button/add.png +0 -0
- data/lib/ozdenui/web/comp/action-button.js +521 -0
- data/lib/ozdenui/web/comp/action-tab-bar.js +383 -0
- data/lib/ozdenui/web/comp/app-bar.js +237 -0
- data/lib/ozdenui/web/comp/badge.js +292 -0
- data/lib/ozdenui/web/comp/bottom-bar.js +555 -0
- data/lib/ozdenui/web/comp/breadcrumbs.js +524 -0
- data/lib/ozdenui/web/comp/canvas.js +652 -0
- data/lib/ozdenui/web/comp/chat-view.js +827 -0
- data/lib/ozdenui/web/comp/check-box.js +490 -0
- data/lib/ozdenui/web/comp/code-editor.js +965 -0
- data/lib/ozdenui/web/comp/color-picker.js +636 -0
- data/lib/ozdenui/web/comp/context-menu.js +951 -0
- data/lib/ozdenui/web/comp/currency-field.js +209 -0
- data/lib/ozdenui/web/comp/data-table/arrow.svg +2 -0
- data/lib/ozdenui/web/comp/data-table.js +937 -0
- data/lib/ozdenui/web/comp/date-picker.js +1055 -0
- data/lib/ozdenui/web/comp/dialog.js +992 -0
- data/lib/ozdenui/web/comp/email-field.js +65 -0
- data/lib/ozdenui/web/comp/file-picker.js +920 -0
- data/lib/ozdenui/web/comp/filters.js +807 -0
- data/lib/ozdenui/web/comp/form.js +602 -0
- data/lib/ozdenui/web/comp/full-screen-select/arrow.svg +2 -0
- data/lib/ozdenui/web/comp/full-screen-select/cancel.svg +2 -0
- data/lib/ozdenui/web/comp/full-screen-select.js +614 -0
- data/lib/ozdenui/web/comp/gauge.js +439 -0
- data/lib/ozdenui/web/comp/graph-box.js +3911 -0
- data/lib/ozdenui/web/comp/grid-group.js +185 -0
- data/lib/ozdenui/web/comp/hold-to-confirm-button/trash-red.png +0 -0
- data/lib/ozdenui/web/comp/hold-to-confirm-button/trash.png +0 -0
- data/lib/ozdenui/web/comp/hold-to-confirm-button.js +289 -0
- data/lib/ozdenui/web/comp/image-view.js +598 -0
- data/lib/ozdenui/web/comp/item-list.js +1740 -0
- data/lib/ozdenui/web/comp/json-editor.js +3221 -0
- data/lib/ozdenui/web/comp/json-view.js +597 -0
- data/lib/ozdenui/web/comp/label-editor.js +1140 -0
- data/lib/ozdenui/web/comp/left-menu/data-table.png +0 -0
- data/lib/ozdenui/web/comp/left-menu/home.png +0 -0
- data/lib/ozdenui/web/comp/left-menu/reports.png +0 -0
- data/lib/ozdenui/web/comp/left-menu/setting.png +0 -0
- data/lib/ozdenui/web/comp/left-menu.js +548 -0
- data/lib/ozdenui/web/comp/line-progress-bar.js +343 -0
- data/lib/ozdenui/web/comp/loading-screen.js +413 -0
- data/lib/ozdenui/web/comp/log-view.js +530 -0
- data/lib/ozdenui/web/comp/login-page.js +685 -0
- data/lib/ozdenui/web/comp/markdown-view.js +1045 -0
- data/lib/ozdenui/web/comp/menu-bar.js +624 -0
- data/lib/ozdenui/web/comp/mini-graph-box.js +492 -0
- data/lib/ozdenui/web/comp/minimal-accent.js +208 -0
- data/lib/ozdenui/web/comp/notice.js +229 -0
- data/lib/ozdenui/web/comp/number-field.js +128 -0
- data/lib/ozdenui/web/comp/numeric-keyboard.js +298 -0
- data/lib/ozdenui/web/comp/page-control.js +762 -0
- data/lib/ozdenui/web/comp/page-header.js +191 -0
- data/lib/ozdenui/web/comp/password-field/hide-btn.png +0 -0
- data/lib/ozdenui/web/comp/password-field/hide-btn2.png +0 -0
- data/lib/ozdenui/web/comp/password-field/show-btn.png +0 -0
- data/lib/ozdenui/web/comp/password-field/show-btn2.png +0 -0
- data/lib/ozdenui/web/comp/password-field.js +192 -0
- data/lib/ozdenui/web/comp/period-bar.js +436 -0
- data/lib/ozdenui/web/comp/phone-field.js +322 -0
- data/lib/ozdenui/web/comp/progress-bar.js +992 -0
- data/lib/ozdenui/web/comp/property-panel.js +3639 -0
- data/lib/ozdenui/web/comp/radio-button.js +527 -0
- data/lib/ozdenui/web/comp/range-slider.js +569 -0
- data/lib/ozdenui/web/comp/rich-text-editor.js +1064 -0
- data/lib/ozdenui/web/comp/scroll-area.js +308 -0
- data/lib/ozdenui/web/comp/scrolling-text.js +297 -0
- data/lib/ozdenui/web/comp/search-input/clear-round.svg +1 -0
- data/lib/ozdenui/web/comp/search-input/clear.svg +1 -0
- data/lib/ozdenui/web/comp/search-input/filter.png +0 -0
- data/lib/ozdenui/web/comp/search-input/filter.svg +1 -0
- data/lib/ozdenui/web/comp/search-input/search.svg +1 -0
- data/lib/ozdenui/web/comp/search-input.js +725 -0
- data/lib/ozdenui/web/comp/search-results.js +596 -0
- data/lib/ozdenui/web/comp/select-box.js +1862 -0
- data/lib/ozdenui/web/comp/settings-row.js +299 -0
- data/lib/ozdenui/web/comp/side-panel.js +616 -0
- data/lib/ozdenui/web/comp/slider-field.js +952 -0
- data/lib/ozdenui/web/comp/slider.js +838 -0
- data/lib/ozdenui/web/comp/smart-button/alert-black.png +0 -0
- data/lib/ozdenui/web/comp/smart-button/clock.png +0 -0
- data/lib/ozdenui/web/comp/smart-button.js +981 -0
- data/lib/ozdenui/web/comp/smart-table/clock.png +0 -0
- data/lib/ozdenui/web/comp/smart-table/down.png +0 -0
- data/lib/ozdenui/web/comp/smart-table/scroll.png +0 -0
- data/lib/ozdenui/web/comp/smart-table/sort.png +0 -0
- data/lib/ozdenui/web/comp/smart-table/up.png +0 -0
- data/lib/ozdenui/web/comp/smart-table.js +1883 -0
- data/lib/ozdenui/web/comp/sortable-list.js +1181 -0
- data/lib/ozdenui/web/comp/spark-line-box.js +738 -0
- data/lib/ozdenui/web/comp/splitter.js +411 -0
- data/lib/ozdenui/web/comp/status-bar.js +408 -0
- data/lib/ozdenui/web/comp/step-bar.js +345 -0
- data/lib/ozdenui/web/comp/stepper.js +753 -0
- data/lib/ozdenui/web/comp/tabs.js +1366 -0
- data/lib/ozdenui/web/comp/tag-input.js +1107 -0
- data/lib/ozdenui/web/comp/tap-effect.js +170 -0
- data/lib/ozdenui/web/comp/text-area-field.js +233 -0
- data/lib/ozdenui/web/comp/text-field.js +1006 -0
- data/lib/ozdenui/web/comp/time-line.js +398 -0
- data/lib/ozdenui/web/comp/time-picker.js +1032 -0
- data/lib/ozdenui/web/comp/tiny-select/arrow.svg +1 -0
- data/lib/ozdenui/web/comp/tiny-select.js +322 -0
- data/lib/ozdenui/web/comp/tiny-table.js +283 -0
- data/lib/ozdenui/web/comp/toast.js +891 -0
- data/lib/ozdenui/web/comp/toggle.js +757 -0
- data/lib/ozdenui/web/comp/tool-bar.js +760 -0
- data/lib/ozdenui/web/comp/tooltip.js +534 -0
- data/lib/ozdenui/web/comp/tree-view.js +1179 -0
- data/lib/ozdenui/web/comp/ui-effects.js +1097 -0
- data/lib/ozdenui/web/comp/ui-standards.js +403 -0
- data/lib/ozdenui/web/comp/url-field.js +190 -0
- data/lib/ozdenui/web/comp/web-view.js +588 -0
- data/lib/ozdenui/web/components.js +123 -0
- data/lib/ozdenui/web/index.html +39 -0
- data/lib/ozdenui/window.rb +188 -0
- data/lib/ozdenui/window_cocoa.rb +221 -0
- data/lib/ozdenui.rb +32 -0
- metadata +200 -0
|
@@ -0,0 +1,3911 @@
|
|
|
1
|
+
/* Bismillah */
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
|
|
5
|
+
GraphBox - v26.11
|
|
6
|
+
|
|
7
|
+
NEW PROJECTS: the chart of new pages and projects, with theme: "dark" on a dark page. The model
|
|
8
|
+
page is 02-comp-examples/graph-box.htm. A small box with a number and a graph stays MiniGraphBox / SparkLineBox.
|
|
9
|
+
|
|
10
|
+
UI COMPONENT
|
|
11
|
+
- Charts with no library: this one file draws the whole chart as one SVG. No Chart.js, no other file, no internet.
|
|
12
|
+
(An old page of ChartBox, the bridge to Chart.js, can move over: see below.)
|
|
13
|
+
- Chart types: "line", "area", "bar" (more than one dataset: bars side by side; stacked: 1 one on the other;
|
|
14
|
+
horizontal: 1 bars that grow to the right), "pie", "doughnut" (the first dataset: a part of the whole), "radar",
|
|
15
|
+
"scatter" and "bubble" (two number axes: data: [{ x: 1, y: 2 }]).
|
|
16
|
+
- Light and dark themes ("light", "dark", "auto"), and "minimal", "minimalDark" (the lines of _designs/minimal-theme.htm:
|
|
17
|
+
its colors and its shapes: smaller texts, less round, thin lines). A dataset gets its color from the theme and keeps it,
|
|
18
|
+
also when another dataset is hidden or removed.
|
|
19
|
+
- The axis finds clean numbers by itself (0, 20K, 40K...). A label that has no room is skipped (a line chart: time)
|
|
20
|
+
or it turns (a bar chart: every bar needs its name).
|
|
21
|
+
- Mouse, touch and keyboard: a tooltip with every dataset at that place. (Left / right arrows, Escape, Enter.)
|
|
22
|
+
- The legend hides and shows a dataset (or a slice of a pie) with a click.
|
|
23
|
+
- targetLines: a line of a goal or a limit over the chart, with no dataset: [{ value: 90000, label: "Target" }]. The axis
|
|
24
|
+
holds it, and the tooltip shows it next to the values.
|
|
25
|
+
- maxSlices: a pie with too many slices can not be read, so its smallest slices become one "Other" slice. The tooltip
|
|
26
|
+
names them and the table keeps every one of them.
|
|
27
|
+
- showValues: 1: the values on the chart, only where they fit: at the end of a bar, in a part of a stack, in a slice,
|
|
28
|
+
at the end of a line. A value that has no room stays in the tooltip and in the table.
|
|
29
|
+
- setTableView(1): the same values as a table. A chart can not be read by everyone (a color, a screen reader); this
|
|
30
|
+
can. getTableData() gives its rows.
|
|
31
|
+
- getImage() and download("chart.png"): the whole card as a picture.
|
|
32
|
+
- animated: 1: a change of the data moves the marks to their new places, a new value of a live chart slides in, the
|
|
33
|
+
tooltip follows softly. No motion at the first view, and none when the system asks for less motion.
|
|
34
|
+
|
|
35
|
+
USAGE:
|
|
36
|
+
const sales = GraphBox({
|
|
37
|
+
width: 500, height: 300,
|
|
38
|
+
type: "bar",
|
|
39
|
+
titleText: "Sales",
|
|
40
|
+
labels: ["Jan", "Feb", "Mar"],
|
|
41
|
+
values: [12, 19, 7], // Shortcut for one dataset. Or: datasets: [{ label: "2026", data: [12, 19, 7] }]
|
|
42
|
+
formatValue: (value) => value + " ₺",
|
|
43
|
+
onClick: (self, item) => println(item.label + ": " + item.value),
|
|
44
|
+
});
|
|
45
|
+
sales.addValue("Apr", 15);
|
|
46
|
+
sales.setTheme("dark");
|
|
47
|
+
|
|
48
|
+
A SCATTER DATASET: { label: "Group A", data: [{ x: 170, y: 65, label: "Ayşe" }, [182, 80]] }
|
|
49
|
+
- A bubble has a size too: { x: 170, y: 65, r: 12 } or [170, 65, 12]. (Its area follows the value.)
|
|
50
|
+
- graph.addPoint({ x: 1, y: 2 }, 0) adds a point to a dataset.
|
|
51
|
+
|
|
52
|
+
A DATASET: { label: "2026", data: [12, null, 7], color: "#2A78D6", type: "line" }
|
|
53
|
+
- null in data: no value at that place (a line breaks there).
|
|
54
|
+
- color: its own color. colors: [...]: a color for each bar.
|
|
55
|
+
- type: "line", "area", "bar" (only this dataset; the others keep the type of the chart: a mixed chart).
|
|
56
|
+
- fill: 1 (a soft area under the line), "gradient" (it fades towards the base line). fillTo: "start": the area ends at
|
|
57
|
+
the start of the axis, not at 0. (Ex: a cold room: under 0 an area up to 0 would fill the part over the line.)
|
|
58
|
+
- showInLegend: 0: no item in the legend.
|
|
59
|
+
- curve: "linear", "smooth". dashed: 1 (Ex: a target). showPoints: 1, 0, "auto". hidden: 1.
|
|
60
|
+
|
|
61
|
+
MOVING A PAGE FROM ChartBox: the same functions (setType, setValues, addValue, setData, update, setTheme, download...)
|
|
62
|
+
and these changes:
|
|
63
|
+
- title, subtitle -> titleText, subtitleText. style.chart -> style.colors.
|
|
64
|
+
- In a dataset: tension -> curve: "smooth". borderDash -> dashed: 1. pointRadius: 0 -> showPoints: 0.
|
|
65
|
+
borderColor / backgroundColor -> color. fill: true -> fill: 1. ChartBox.gradient() -> fill: "gradient".
|
|
66
|
+
- options.scales.y.max -> maxValue. suggestedMax -> softMaxValue. ticks.stepSize -> valueStep.
|
|
67
|
+
options.scales.x.ticks.maxTicksLimit -> maxLabels. options.cutout -> style.pie.hole.
|
|
68
|
+
options.elements.point.radius: 0 -> showPoints: 0. A color for each slice: backgroundColor: [...] -> colors: [...].
|
|
69
|
+
fill: "start" -> fillTo: "start". maxBarThickness -> style.bar.maxThickness. A legend filter -> showInLegend: 0.
|
|
70
|
+
- There is no options, plugins and box.chart: this is not Chart.js. A chart with two value axes can not be made, on purpose:
|
|
71
|
+
where two scales meet is free, so it shows a relation that is not in the data. (Two charts, one under the other.)
|
|
72
|
+
- "polarArea" is not here yet.
|
|
73
|
+
|
|
74
|
+
NEEDS: basic.js v26.10.25 (basic.resolveTheme, listenTo, setFocusRing...).
|
|
75
|
+
|
|
76
|
+
Started Date: November 2026
|
|
77
|
+
Webpage: https://bug7a.github.io/js-components/
|
|
78
|
+
|
|
79
|
+
Copyright 2020-2026 Bugra Ozden <bugra.ozden@gmail.com> (https://bug7a.github.io/)
|
|
80
|
+
Licensed under the Apache License, Version 2.0
|
|
81
|
+
SPDX-License-Identifier: Apache-2.0
|
|
82
|
+
|
|
83
|
+
*/
|
|
84
|
+
|
|
85
|
+
"use strict";
|
|
86
|
+
|
|
87
|
+
// Default values:
|
|
88
|
+
const GraphBoxDefaults = {
|
|
89
|
+
key: "0",
|
|
90
|
+
width: 500,
|
|
91
|
+
height: 300,
|
|
92
|
+
type: "line", // "line", "area", "bar", "pie", "doughnut", "radar", "scatter", "bubble"
|
|
93
|
+
theme: "light", // "light", "dark", "auto" (follows the system setting), "minimal", "minimalDark"
|
|
94
|
+
titleText: "",
|
|
95
|
+
subtitleText: "",
|
|
96
|
+
labels: null, // ["Jan", "Feb", "Mar"]
|
|
97
|
+
values: null, // [12, 19, 7] Shortcut: creates one dataset.
|
|
98
|
+
datasets: null, // [{ label: "2026", data: [12, 19, 7], ...see A DATASET above }]
|
|
99
|
+
data: null, // { labels, datasets } (Used instead of labels, values and datasets.)
|
|
100
|
+
// "auto" (2+ datasets; a pie: at the right, or at the bottom of a narrow box), "top", "bottom", "left", "right", "none"
|
|
101
|
+
legend: "auto",
|
|
102
|
+
stacked: 0, // 1: Bars one on the other, lines and areas over each other. The tooltip adds totalText.
|
|
103
|
+
horizontal: 0, // 1: The values grow to the right. (Long names read better so.)
|
|
104
|
+
totalText: "Total", // The last row of the tooltip of a stacked chart. "": No total
|
|
105
|
+
targetLines: null, // [{ value: 90000, label: "Target", color: "" }] No label: its value. label: "": No text.
|
|
106
|
+
maxSlices: 8, // A pie, a doughnut: at most this many slices; the smallest ones become "Other". 0: No limit.
|
|
107
|
+
otherText: "Other", // The name of that slice
|
|
108
|
+
centerText: "", // The big text in the middle of a doughnut. Ex: "1,284"
|
|
109
|
+
centerSubText: "", // The small text under it. Ex: "Users"
|
|
110
|
+
beginAtZero: 1, // 1: The value axis holds 0. (A bar chart always holds it: the length of a bar is its value.)
|
|
111
|
+
minValue: null, // null: From the values.
|
|
112
|
+
maxValue: null, // null: From the values. Ex: 100
|
|
113
|
+
softMinValue: null, // The axis goes at least this low. Unlike minValue, a smaller value still widens it.
|
|
114
|
+
softMaxValue: null, // The axis goes at least this high. Ex: 260
|
|
115
|
+
valueStep: 0, // 0: The axis finds its own step. Ex: 1: a line and a text for every whole number.
|
|
116
|
+
minX: null, // scatter, bubble: the limits of the x axis. null: From the values. (They do not hold 0 by themselves.)
|
|
117
|
+
maxX: null,
|
|
118
|
+
sizeText: "Size", // bubble: the name of its size in the tooltip
|
|
119
|
+
xAxisText: "", // A small title under the chart. Ex: "Height (cm)"
|
|
120
|
+
yAxisText: "", // A small title at the left of the chart, turned. Ex: "Weight (kg)"
|
|
121
|
+
showValues: 0, // 1: The values on the chart, only where they fit.
|
|
122
|
+
tableView: 0, // 1: A table of the values in place of the chart. setTableView()
|
|
123
|
+
tableHeadText: "", // The title of the first column of the table
|
|
124
|
+
maxLabels: 0, // At most this many labels on the index axis. 0: As many as fit.
|
|
125
|
+
curve: "linear", // "linear", "smooth" (never goes over a value)
|
|
126
|
+
showPoints: "auto", // "auto": When there is room for them. 1, 0
|
|
127
|
+
formatValue: null, // function (value) { return value + " ₺"; } For the tooltip and the value axis.
|
|
128
|
+
formatX: null, // scatter, bubble: the same for the x axis.
|
|
129
|
+
locale: "", // "": The language of the browser. Ex: "tr-TR"
|
|
130
|
+
maxCount: 0, // addValue(): 0: No limit. Ex: 20 (the first value is removed, for live data)
|
|
131
|
+
emptyText: "No data", // In the middle of a chart with no values. "": Nothing
|
|
132
|
+
animated: 0, // 1: Small motions when the data changes. setAnimated()
|
|
133
|
+
onClick: function (self, item, event) { }, // item: { datasetIndex, index, label, value, datasetLabel, dataset }
|
|
134
|
+
style: {
|
|
135
|
+
box: {
|
|
136
|
+
color: "", // "": The backgroundColor of the theme
|
|
137
|
+
border: 1,
|
|
138
|
+
borderColor: "", // "": The borderColor of the theme
|
|
139
|
+
round: 12,
|
|
140
|
+
padding: 16,
|
|
141
|
+
gap: 12, // Between the texts, the legend and the chart
|
|
142
|
+
},
|
|
143
|
+
colors: {
|
|
144
|
+
// Changes some colors of the theme. Ex: { gridColor: "#334155", colors: ["#38BDF8", "#8B5CF6"] }
|
|
145
|
+
},
|
|
146
|
+
title: { fontSize: 16, fontFamily: "opensans-bold" },
|
|
147
|
+
subtitle: { fontSize: 12 },
|
|
148
|
+
legend: {
|
|
149
|
+
keys: {
|
|
150
|
+
line: { width: 14, height: 2, round: 1 },
|
|
151
|
+
box: { width: 10, height: 10, round: 2 },
|
|
152
|
+
dot: { width: 8, height: 8, round: 4 },
|
|
153
|
+
},
|
|
154
|
+
fontSize: 12,
|
|
155
|
+
gap: 14,
|
|
156
|
+
lineGap: 6,
|
|
157
|
+
keyGap: 6,
|
|
158
|
+
hiddenOpacity: 0.4,
|
|
159
|
+
sideMinWidth: 400, // A pie: the legend is at its side only in a box as wide as this.
|
|
160
|
+
maxSideShare: "45%", // The legend at a side
|
|
161
|
+
maxLinesShare: "40%", // The legend over or under the chart
|
|
162
|
+
},
|
|
163
|
+
axis: {
|
|
164
|
+
fontSize: 12,
|
|
165
|
+
fontFamily: "opensans, system-ui, -apple-system, 'Segoe UI', sans-serif",
|
|
166
|
+
labelGap: 8, // Between a text of the axis and the chart
|
|
167
|
+
tickSpace: 32, // At least this many px between two lines of the value axis
|
|
168
|
+
sideTickSpace: 90, // The same on an axis that runs to the right: its numbers are side by side.
|
|
169
|
+
labelSpace: 10, // At least this many px between two labels
|
|
170
|
+
labelAngle: 35, // Degrees. The labels of the bars turn when they have no room. 0: A label is skipped instead.
|
|
171
|
+
maxLabelShare: 0.3, // A turned label is cut with "..." at this much of the height of the chart.
|
|
172
|
+
maxSideLabelShare: 0.35, // horizontal: 1: a label is cut with "..." at this much of the width of the chart.
|
|
173
|
+
},
|
|
174
|
+
bar: {
|
|
175
|
+
maxThickness: 24,
|
|
176
|
+
round: 4, // Only at the end of the value. The base stays square.
|
|
177
|
+
gap: 2, // Between two bars side by side, and between two values of a stack
|
|
178
|
+
minLength: 1, // A very small value is still this long.
|
|
179
|
+
bandShare: 0.72, // How much of its place a group of bars can fill
|
|
180
|
+
},
|
|
181
|
+
line: {
|
|
182
|
+
width: 2,
|
|
183
|
+
pointRadius: 4,
|
|
184
|
+
pointRing: 2, // The ring in the color of the box, so a point stays clear where lines cross
|
|
185
|
+
pointSpace: 18, // showPoints "auto": points only when two values are this many px apart
|
|
186
|
+
fillOpacity: 0.1,
|
|
187
|
+
gradientOpacity: 0.3, // At the top of a "gradient" fill
|
|
188
|
+
dash: "5 5",
|
|
189
|
+
changeOpacity: 0.3, // animated: 1: where a line can not move (Safari), it comes from this opacity.
|
|
190
|
+
},
|
|
191
|
+
target: {
|
|
192
|
+
width: 1.5,
|
|
193
|
+
dash: "6 4", // WHY dashed: A goal or a limit is not a value. A line of the grid is never dashed.
|
|
194
|
+
labelGap: 3, // Between the line and its text
|
|
195
|
+
},
|
|
196
|
+
pie: {
|
|
197
|
+
otherRows: 5, // How many of the small slices the tooltip of "Other" names
|
|
198
|
+
gap: 2, // Between two slices
|
|
199
|
+
hole: 0.62, // A doughnut: the hole, as a part of the radius
|
|
200
|
+
hoverGrow: 4, // Px: the slice under the mouse
|
|
201
|
+
changeOpacity: 0.4, // animated: 1: a slice comes from this opacity when the values change.
|
|
202
|
+
centerFontSize: 26,
|
|
203
|
+
},
|
|
204
|
+
radar: {
|
|
205
|
+
ringSpace: 16, // At least this many px between two rings
|
|
206
|
+
fillOpacity: 0.15,
|
|
207
|
+
maxLabelShare: 0.28, // A label is cut with "..." at this much of the width of the chart.
|
|
208
|
+
showTicks: 1, // 1: The numbers of the rings
|
|
209
|
+
},
|
|
210
|
+
scatter: {
|
|
211
|
+
maxBubble: 22, // Px: the radius of the biggest bubble
|
|
212
|
+
bubbleOpacity: 0.65,
|
|
213
|
+
hitRadius: 14, // Px: the mouse finds a point this far from it. (A point of 8 px is too small to aim at.)
|
|
214
|
+
},
|
|
215
|
+
values: {
|
|
216
|
+
gap: 4, // Between a mark and its value
|
|
217
|
+
sidePadding: 3, // A value in a mark needs this much room at its sides.
|
|
218
|
+
},
|
|
219
|
+
table: {
|
|
220
|
+
fontSize: 12,
|
|
221
|
+
rowHeight: 28,
|
|
222
|
+
cellPadding: 8,
|
|
223
|
+
headFontFamily: "opensans-bold",
|
|
224
|
+
},
|
|
225
|
+
tooltip: {
|
|
226
|
+
fontSize: 12,
|
|
227
|
+
round: 6,
|
|
228
|
+
padding: [10, 8],
|
|
229
|
+
gap: 4,
|
|
230
|
+
keyWidth: 12,
|
|
231
|
+
keyHeight: 3,
|
|
232
|
+
distance: 14, // Between the mouse and the tooltip
|
|
233
|
+
edge: 4, // It stays this many px inside the box.
|
|
234
|
+
maxNameWidth: 180,
|
|
235
|
+
shadow: "0 4px 14px rgba(0, 0, 0, 0.18)",
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
const GraphBox = function (params = {}) {
|
|
241
|
+
|
|
242
|
+
// WHY: The other components take styleName; a chart takes theme (the colors, also "auto") and style (the shapes).
|
|
243
|
+
// Without this line a styleName is kept quietly and the chart stays light.
|
|
244
|
+
if (params.styleName) console.warn("GraphBox: styleName is not used. The colors come with theme (\"light\", \"dark\", \"auto\", \"minimal\", \"minimalDark\"), the shapes with style.");
|
|
245
|
+
|
|
246
|
+
// Merge params: the shapes of its theme (GraphBox.THEMES[name].style: minimal), then the defaults
|
|
247
|
+
// WHY before the defaults: the shapes of a theme win over the default shapes, a style of the page over both
|
|
248
|
+
const themeOfParams = GraphBox.THEMES[params.theme];
|
|
249
|
+
if (themeOfParams && themeOfParams.style) {
|
|
250
|
+
const ownStyle = {};
|
|
251
|
+
mergeIntoIfMissing(ownStyle, params.style || {});
|
|
252
|
+
mergeIntoIfMissing(ownStyle, themeOfParams.style);
|
|
253
|
+
params.style = ownStyle;
|
|
254
|
+
}
|
|
255
|
+
mergeIntoIfMissing(params, GraphBoxDefaults);
|
|
256
|
+
|
|
257
|
+
// WHY: startObject() keeps the arrays of the page by reference. The data is kept out of it: box.data is a copy.
|
|
258
|
+
const dataParams = { labels: params.labels, values: params.values, datasets: params.datasets, data: params.data };
|
|
259
|
+
const boxParams = Object.assign({}, params);
|
|
260
|
+
Object.keys(dataParams).forEach(function (key) { delete boxParams[key]; });
|
|
261
|
+
|
|
262
|
+
// BOX: Component container
|
|
263
|
+
const box = startObject(boxParams);
|
|
264
|
+
|
|
265
|
+
// *** PRIVATE VARIABLES:
|
|
266
|
+
let _s = box.style;
|
|
267
|
+
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
268
|
+
const MOTION_TIME = 0.25; // Seconds
|
|
269
|
+
const TOOLTIP_CLOSE_TIME = 0.15;
|
|
270
|
+
const MOTION_EASE = "cubic-bezier(0.2, 0.8, 0.2, 1)";
|
|
271
|
+
const LEGEND_FLOWS = { top: "column", bottom: "column-reverse", left: "row", right: "row-reverse" };
|
|
272
|
+
const STEP_KEYS = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 };
|
|
273
|
+
const hasClickEvent = (box.onClick !== GraphBoxDefaults.onClick);
|
|
274
|
+
const SUMMARY_VALUE_COUNT = 100;
|
|
275
|
+
const FULL_CIRCLE = Math.PI * 2;
|
|
276
|
+
const TOP_ANGLE = -Math.PI / 2; // The first slice starts at the top.
|
|
277
|
+
const colorIndexes = new Map(); // The key of a series -> its place in the colors of the theme
|
|
278
|
+
const sliceColorIndexes = new Map(); // The same for the slices of a pie
|
|
279
|
+
const hiddenSliceKeys = new Set(); // WHY keys, not places: A slice stays hidden when the values come again.
|
|
280
|
+
const tooltipRows = [];
|
|
281
|
+
let colors = null; // The colors of the theme + style.colors
|
|
282
|
+
let svg, definitions, gridLayer, washLayer, clipLayer, markLayer, overlayLayer, valueLayer;
|
|
283
|
+
let view = null; // What the last drawing knows about its marks. null: nothing is drawn.
|
|
284
|
+
let activeItem = null; // { index, datasetIndex }: under the mouse, or chosen with the keyboard.
|
|
285
|
+
let pointer = null; // { x, y } in the plot. null: the keyboard chose the item.
|
|
286
|
+
let legendSignature = "";
|
|
287
|
+
let drawnSize = "";
|
|
288
|
+
let legendPlace = "";
|
|
289
|
+
let marks = new Map(); // What the last drawing made: its name -> { shape, rect or point }. (For the motion)
|
|
290
|
+
let drawnAxes = null; // The axes of the last drawing of a line or bar chart. (For the motion)
|
|
291
|
+
let isChangeWaiting = 0; // 1: The next drawing shows a change of the data, so it can move.
|
|
292
|
+
let addedValueShift = null; // A number: addValue() is waiting to be drawn; so many old values went out at the left.
|
|
293
|
+
let isTooltipShown = 0;
|
|
294
|
+
let cancelTooltipHide = null;
|
|
295
|
+
|
|
296
|
+
// *** PUBLIC VARIABLES:
|
|
297
|
+
// [var] { labels, datasets } A copy of the data of the page. After a change: box.update()
|
|
298
|
+
box.data = null;
|
|
299
|
+
// [var] The SVG element of the chart
|
|
300
|
+
box.svg = null;
|
|
301
|
+
// [var] The objects of the legend
|
|
302
|
+
box.legendItems = [];
|
|
303
|
+
|
|
304
|
+
// *** PRIVATE FUNCTIONS:
|
|
305
|
+
|
|
306
|
+
// DRAWING: each function does one job, and a change calls only the one it needs:
|
|
307
|
+
// applyLook() -> the colors of the card and the texts (setTheme, setStyle)
|
|
308
|
+
// applyContent() -> the title and the subtitle (setTitleText, setSubtitleText)
|
|
309
|
+
// createLegend() -> the items of the legend, from the data (the data changed)
|
|
310
|
+
// drawPlot() -> the SVG: the axes and the marks (the data or the size changed)
|
|
311
|
+
// paintActiveItem() -> the mark under the mouse and the tooltip (the mouse or the keyboard moved)
|
|
312
|
+
// refreshLayout() -> the place of the legend and drawPlot() (resize)
|
|
313
|
+
// drawData() -> what comes from the data (box.update)
|
|
314
|
+
// drawAll() -> all of them (the first drawing)
|
|
315
|
+
// WHY: The mouse only moves the things in overlayLayer and the tooltip; the marks are not made again for it.
|
|
316
|
+
|
|
317
|
+
// DATA:
|
|
318
|
+
|
|
319
|
+
// WHY copies: addValue() and maxCount must not change the arrays of the page.
|
|
320
|
+
const copyDataset = function (dataset) {
|
|
321
|
+
return Object.assign({}, dataset, { data: (dataset.data || []).slice() });
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
const copyData = function (data) {
|
|
325
|
+
return {
|
|
326
|
+
labels: (data.labels || []).slice(),
|
|
327
|
+
datasets: (data.datasets || []).map(copyDataset),
|
|
328
|
+
};
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
const createData = function () {
|
|
332
|
+
if (dataParams.data) return copyData(dataParams.data);
|
|
333
|
+
let datasets = dataParams.datasets;
|
|
334
|
+
if (!datasets && dataParams.values) datasets = [{ data: dataParams.values }];
|
|
335
|
+
return copyData({ labels: dataParams.labels, datasets: datasets });
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
// A number, or null. (A number in a text is a number; an empty place, a wrong text: null.)
|
|
339
|
+
const toNumber = function (value) {
|
|
340
|
+
if (value === null || value === undefined || value === "") return null;
|
|
341
|
+
const number = Number(value);
|
|
342
|
+
return (isFinite(number)) ? number : null;
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
const getValue = function (dataset, index) {
|
|
346
|
+
return toNumber(dataset.data[index]);
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
const getLabelText = function (index) {
|
|
350
|
+
const label = box.data.labels[index];
|
|
351
|
+
return (label === undefined || label === null) ? "" : String(label);
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
// TEXTS OF THE NUMBERS:
|
|
355
|
+
|
|
356
|
+
const formatValueText = function (value) {
|
|
357
|
+
if (box.formatValue) return String(box.formatValue(value));
|
|
358
|
+
return GraphBox.formatNumber(value, box.locale);
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
const formatTickText = function (value, decimals) {
|
|
362
|
+
if (box.formatValue) return String(box.formatValue(value));
|
|
363
|
+
return GraphBox.formatCompactNumber(value, box.locale, decimals);
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
// COLORS:
|
|
367
|
+
|
|
368
|
+
const getSeriesKey = function (dataset, position) {
|
|
369
|
+
return dataset.label || ("#" + position);
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
// WHY: A color follows its series, not its place in the list: a reader who learned "Target is orange" must not
|
|
373
|
+
// be misled when another series is removed. So a new series takes the first free color.
|
|
374
|
+
const assignColorIndexes = function (keys, indexes) {
|
|
375
|
+
|
|
376
|
+
const takenIndexes = new Set();
|
|
377
|
+
|
|
378
|
+
keys.forEach(function (key) {
|
|
379
|
+
if (indexes.has(key)) takenIndexes.add(indexes.get(key));
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
keys.forEach(function (key) {
|
|
383
|
+
if (indexes.has(key)) return;
|
|
384
|
+
let freeIndex = 0;
|
|
385
|
+
while (takenIndexes.has(freeIndex)) freeIndex++;
|
|
386
|
+
takenIndexes.add(freeIndex);
|
|
387
|
+
indexes.set(key, freeIndex);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
const assignColors = function () {
|
|
393
|
+
const seriesKeys = box.data.datasets.map(function (dataset, position) {
|
|
394
|
+
return getSeriesKey(dataset, position);
|
|
395
|
+
});
|
|
396
|
+
assignColorIndexes(seriesKeys, colorIndexes);
|
|
397
|
+
if (isPieType()) assignColorIndexes(getSliceColorKeys(), sliceColorIndexes);
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
// WHY otherColor: Past the eighth color a new hue can not be told from the others. So it is a quiet gray.
|
|
401
|
+
const getSeriesColor = function (dataset, position) {
|
|
402
|
+
if (dataset.color) return dataset.color;
|
|
403
|
+
return colors.colors[colorIndexes.get(getSeriesKey(dataset, position))] || colors.otherColor;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
const getSeriesKeyOf = function (seriesItem) {
|
|
407
|
+
return getSeriesKey(seriesItem.dataset, seriesItem.datasetIndex);
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
const getMarkColor = function (seriesItem, index) {
|
|
411
|
+
const ownColors = seriesItem.dataset.colors;
|
|
412
|
+
return (ownColors && ownColors[index]) || seriesItem.color;
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
const getSurfaceColor = function () {
|
|
416
|
+
return _s.box.color || colors.backgroundColor;
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
// SVG:
|
|
420
|
+
|
|
421
|
+
const createSvgElement = function (name, attributes) {
|
|
422
|
+
const element = document.createElementNS(SVG_NS, name);
|
|
423
|
+
for (const key in attributes) element.setAttribute(key, attributes[key]);
|
|
424
|
+
return element;
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
const addShape = function (layer, name, attributes) {
|
|
428
|
+
const shape = createSvgElement(name, attributes);
|
|
429
|
+
layer.appendChild(shape);
|
|
430
|
+
return shape;
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
const addLine = function (layer, x1, y1, x2, y2, color) {
|
|
434
|
+
return addShape(layer, "line", { x1: x1, y1: y1, x2: x2, y2: y2, stroke: color, "stroke-width": 1 });
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
const addText = function (layer, text, x, y, anchor = "middle", color = colors.mutedTextColor) {
|
|
438
|
+
const shape = addShape(layer, "text", {
|
|
439
|
+
x: x,
|
|
440
|
+
y: y,
|
|
441
|
+
fill: color,
|
|
442
|
+
"text-anchor": anchor,
|
|
443
|
+
"dominant-baseline": "central",
|
|
444
|
+
});
|
|
445
|
+
shape.textContent = text; // WHY: A label is a text of the user, never HTML.
|
|
446
|
+
return shape;
|
|
447
|
+
};
|
|
448
|
+
|
|
449
|
+
const clearLayers = function () {
|
|
450
|
+
[definitions, gridLayer, washLayer, markLayer, overlayLayer, valueLayer].forEach(function (layer) {
|
|
451
|
+
layer.replaceChildren();
|
|
452
|
+
});
|
|
453
|
+
clipLayer.removeAttribute("clip-path");
|
|
454
|
+
overlayLayer.removeAttribute("clip-path");
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
// What a drawing made, by a name that stays the same in the next drawing. geometry: { rect } or { point }
|
|
458
|
+
const rememberMark = function (markType, seriesKey, place, shape, geometry) {
|
|
459
|
+
marks.set(markType + "|" + seriesKey + "|" + place, Object.assign({ shape: shape }, geometry));
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
// A line of 1 px is sharp only in the middle of a pixel.
|
|
463
|
+
const toPixelCenter = function (position) {
|
|
464
|
+
return Math.round(position) + 0.5;
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
const measureAxisText = function (text) {
|
|
468
|
+
return GraphBox.measureText(text, _s.axis.fontSize, _s.axis.fontFamily);
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
// WHY more than the font size: A letter like "J" or "y" goes under it, and the plot box cuts what is out of it.
|
|
472
|
+
const getAxisTextHeight = function () {
|
|
473
|
+
return Math.ceil(_s.axis.fontSize * 1.4);
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
const measureWidestText = function (texts) {
|
|
477
|
+
return texts.reduce(function (widest, text) {
|
|
478
|
+
return Math.max(widest, measureAxisText(text));
|
|
479
|
+
}, 0);
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
// THE SERIES ON THE SCREEN:
|
|
483
|
+
|
|
484
|
+
const getDatasetType = function (dataset) {
|
|
485
|
+
return dataset.type || box.type;
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
const isBarSeries = function (seriesItem) {
|
|
489
|
+
return getDatasetType(seriesItem.dataset) === "bar";
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
const isLineSeries = function (seriesItem) {
|
|
493
|
+
return !isBarSeries(seriesItem);
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
const getVisibleSeries = function () {
|
|
497
|
+
const series = [];
|
|
498
|
+
box.data.datasets.forEach(function (dataset, position) {
|
|
499
|
+
if (basic.isOn(dataset.hidden)) return;
|
|
500
|
+
series.push({ dataset: dataset, datasetIndex: position, color: getSeriesColor(dataset, position) });
|
|
501
|
+
});
|
|
502
|
+
return series;
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
// How many places the index axis has. (A series can be longer than the labels.)
|
|
506
|
+
const getIndexCount = function (series) {
|
|
507
|
+
return series.reduce(function (count, seriesItem) {
|
|
508
|
+
return Math.max(count, seriesItem.dataset.data.length);
|
|
509
|
+
}, box.data.labels.length);
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
const isStacked = function () {
|
|
513
|
+
return (box.stacked == 1 && box.type !== "radar");
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
const getStackName = function (seriesItem, value) {
|
|
517
|
+
if (!isBarSeries(seriesItem)) return "lines";
|
|
518
|
+
return (value < 0) ? "barsUnderBase" : "barsOverBase"; // WHY: A bar under the base line grows on its own side.
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
// Where a value starts and ends on the value axis. A stacked value starts where the one before it ended.
|
|
522
|
+
const createValueRange = function (seriesItem, index, stackTotals) {
|
|
523
|
+
const value = getValue(seriesItem.dataset, index);
|
|
524
|
+
if (value === null) return null;
|
|
525
|
+
if (!isStacked()) return { from: 0, to: value };
|
|
526
|
+
const totals = stackTotals[getStackName(seriesItem, value)];
|
|
527
|
+
const from = totals[index] || 0;
|
|
528
|
+
totals[index] = from + value;
|
|
529
|
+
return { from: from, to: from + value };
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
const addValueRanges = function (series, indexCount) {
|
|
533
|
+
const stackTotals = { lines: [], barsOverBase: [], barsUnderBase: [] };
|
|
534
|
+
series.forEach(function (seriesItem) {
|
|
535
|
+
seriesItem.ranges = [];
|
|
536
|
+
for (let index = 0; index < indexCount; index++) {
|
|
537
|
+
seriesItem.ranges.push(createValueRange(seriesItem, index, stackTotals));
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
const getValueLimits = function (series) {
|
|
543
|
+
|
|
544
|
+
let low = Infinity;
|
|
545
|
+
let high = -Infinity;
|
|
546
|
+
|
|
547
|
+
series.forEach(function (seriesItem) {
|
|
548
|
+
seriesItem.ranges.forEach(function (range) {
|
|
549
|
+
if (!range) return;
|
|
550
|
+
low = Math.min(low, range.to);
|
|
551
|
+
high = Math.max(high, range.to);
|
|
552
|
+
});
|
|
553
|
+
});
|
|
554
|
+
|
|
555
|
+
if (low === Infinity) return null; // No values
|
|
556
|
+
|
|
557
|
+
getHeldValues().forEach(function (value) {
|
|
558
|
+
low = Math.min(low, value);
|
|
559
|
+
high = Math.max(high, value);
|
|
560
|
+
});
|
|
561
|
+
|
|
562
|
+
if (box.beginAtZero == 1 || series.some(isBarSeries)) {
|
|
563
|
+
low = Math.min(low, 0);
|
|
564
|
+
high = Math.max(high, 0);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const limits = applyFixedLimits(low, high, box.minValue, box.maxValue);
|
|
568
|
+
limits.fixedStep = toNumber(box.valueStep);
|
|
569
|
+
return limits;
|
|
570
|
+
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
const applyFixedLimits = function (low, high, fixedLow, fixedHigh) {
|
|
574
|
+
const minValue = toNumber(fixedLow);
|
|
575
|
+
const maxValue = toNumber(fixedHigh);
|
|
576
|
+
return {
|
|
577
|
+
low: (minValue === null) ? low : minValue,
|
|
578
|
+
high: (maxValue === null) ? high : maxValue,
|
|
579
|
+
hasFixedLow: (minValue !== null),
|
|
580
|
+
hasFixedHigh: (maxValue !== null),
|
|
581
|
+
};
|
|
582
|
+
};
|
|
583
|
+
|
|
584
|
+
const createValueScale = function (limits, length, tickSpace = _s.axis.tickSpace, formatTick = formatTickText) {
|
|
585
|
+
const tickCount = Math.max(2, Math.floor(length / tickSpace));
|
|
586
|
+
const scale = GraphBox.niceScale(limits.low, limits.high, tickCount, limits.fixedStep);
|
|
587
|
+
if (limits.hasFixedLow) scale.min = limits.low;
|
|
588
|
+
if (limits.hasFixedHigh) scale.max = limits.high;
|
|
589
|
+
scale.ticks = scale.ticks.filter(function (tick) {
|
|
590
|
+
return (tick >= scale.min && tick <= scale.max);
|
|
591
|
+
});
|
|
592
|
+
scale.tickTexts = scale.ticks.map(function (tick) {
|
|
593
|
+
return formatTick(tick, scale.decimals);
|
|
594
|
+
});
|
|
595
|
+
return scale;
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
// The base of the bars and the areas: 0, or the nearest edge when the axis does not hold 0.
|
|
599
|
+
const getBaseValue = function (scale) {
|
|
600
|
+
return Math.min(scale.max, Math.max(scale.min, 0));
|
|
601
|
+
};
|
|
602
|
+
|
|
603
|
+
// THE TARGET LINES:
|
|
604
|
+
|
|
605
|
+
const getTargetLines = function () {
|
|
606
|
+
return (box.targetLines || []).filter(function (line) {
|
|
607
|
+
return toNumber(line.value) !== null;
|
|
608
|
+
});
|
|
609
|
+
};
|
|
610
|
+
|
|
611
|
+
const getTargetValues = function () {
|
|
612
|
+
return getTargetLines().map(function (line) { return toNumber(line.value); });
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
// What the axis holds, also when no value is there.
|
|
616
|
+
const getHeldValues = function () {
|
|
617
|
+
const softValues = [toNumber(box.softMinValue), toNumber(box.softMaxValue)].filter(function (value) {
|
|
618
|
+
return value !== null;
|
|
619
|
+
});
|
|
620
|
+
return getTargetValues().concat(softValues);
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
// No label: its value. label: "": no text.
|
|
624
|
+
const getTargetText = function (line) {
|
|
625
|
+
return (line.label === undefined) ? formatValueText(toNumber(line.value)) : String(line.label);
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
const getTargetColor = function (line) {
|
|
629
|
+
return line.color || colors.targetColor;
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
// A text with a ring in the color of the box: it stays clear over a line or a bar.
|
|
633
|
+
const addClearText = function (layer, text, x, y, anchor, color) {
|
|
634
|
+
const label = addText(layer, text, x, y, anchor, color);
|
|
635
|
+
label.setAttribute("stroke", getSurfaceColor());
|
|
636
|
+
label.setAttribute("stroke-width", 3);
|
|
637
|
+
label.setAttribute("paint-order", "stroke");
|
|
638
|
+
return label;
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
// Over the line at its right end; under it when there is no room over it.
|
|
642
|
+
const addUprightTargetText = function (text, plot, position) {
|
|
643
|
+
const textHeight = getAxisTextHeight();
|
|
644
|
+
const distance = textHeight / 2 + _s.target.labelGap;
|
|
645
|
+
const y = (position - distance - textHeight / 2 >= 0) ? position - distance : position + distance;
|
|
646
|
+
addClearText(valueLayer, text, plot.right, y, "end", colors.textColor);
|
|
647
|
+
};
|
|
648
|
+
|
|
649
|
+
// At the top, at the right of the line; at its left when there is no room at its right.
|
|
650
|
+
const addSidewaysTargetText = function (text, plot, position) {
|
|
651
|
+
const y = plot.top + getAxisTextHeight() / 2;
|
|
652
|
+
const distance = _s.target.labelGap + 1;
|
|
653
|
+
const hasRoom = (position + distance + measureAxisText(text) <= plot.right);
|
|
654
|
+
const x = (hasRoom) ? position + distance : position - distance;
|
|
655
|
+
addClearText(valueLayer, text, x, y, (hasRoom) ? "start" : "end", colors.textColor);
|
|
656
|
+
};
|
|
657
|
+
|
|
658
|
+
const drawTargetLine = function (line, linePlace, plot, position, isSideways) {
|
|
659
|
+
|
|
660
|
+
const start = (isSideways) ? { x: position, y: plot.top } : { x: plot.left, y: position };
|
|
661
|
+
const end = (isSideways) ? { x: position, y: plot.bottom } : { x: plot.right, y: position };
|
|
662
|
+
const shape = addShape(markLayer, "line", {
|
|
663
|
+
x1: start.x,
|
|
664
|
+
y1: start.y,
|
|
665
|
+
x2: end.x,
|
|
666
|
+
y2: end.y,
|
|
667
|
+
stroke: getTargetColor(line),
|
|
668
|
+
"stroke-width": _s.target.width,
|
|
669
|
+
"stroke-dasharray": _s.target.dash,
|
|
670
|
+
});
|
|
671
|
+
rememberMark("target", linePlace, 0, shape, { point: start });
|
|
672
|
+
|
|
673
|
+
const text = getTargetText(line);
|
|
674
|
+
if (!text) return;
|
|
675
|
+
if (isSideways) addSidewaysTargetText(text, plot, position);
|
|
676
|
+
else addUprightTargetText(text, plot, position);
|
|
677
|
+
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// toPosition: the place of a value on the value axis. A line out of the scale (a fixed limit) is not drawn.
|
|
681
|
+
const drawTargetLines = function (plot, scale, toPosition, isSideways) {
|
|
682
|
+
getTargetLines().forEach(function (line, linePlace) {
|
|
683
|
+
const value = toNumber(line.value);
|
|
684
|
+
if (value < scale.min || value > scale.max) return;
|
|
685
|
+
drawTargetLine(line, linePlace, plot, toPosition(value), isSideways);
|
|
686
|
+
});
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
// THE VALUES ON THE CHART:
|
|
690
|
+
|
|
691
|
+
const getLastValue = function (seriesItem) {
|
|
692
|
+
for (let index = seriesItem.dataset.data.length - 1; index >= 0; index--) {
|
|
693
|
+
const value = getValue(seriesItem.dataset, index);
|
|
694
|
+
if (value !== null) return value;
|
|
695
|
+
}
|
|
696
|
+
return null;
|
|
697
|
+
};
|
|
698
|
+
|
|
699
|
+
// The texts at the far end of the chart: the last value of a line, every value of a sideways bar.
|
|
700
|
+
const getEndValueTexts = function (series) {
|
|
701
|
+
const isSideways = (box.horizontal == 1);
|
|
702
|
+
const texts = [];
|
|
703
|
+
series.forEach(function (seriesItem) {
|
|
704
|
+
if (!isBarSeries(seriesItem)) {
|
|
705
|
+
const lastValue = getLastValue(seriesItem);
|
|
706
|
+
if (lastValue !== null && !isSideways) texts.push(formatValueText(lastValue));
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
if (!isSideways || isStacked()) return;
|
|
710
|
+
seriesItem.dataset.data.forEach(function (value) {
|
|
711
|
+
const number = toNumber(value);
|
|
712
|
+
if (number !== null) texts.push(formatValueText(number));
|
|
713
|
+
});
|
|
714
|
+
});
|
|
715
|
+
return texts;
|
|
716
|
+
};
|
|
717
|
+
|
|
718
|
+
// The texts of the values of the bars under the base line: they are between the plot and the labels.
|
|
719
|
+
const getUnderBaseTexts = function (series) {
|
|
720
|
+
if (isStacked()) return [];
|
|
721
|
+
const texts = [];
|
|
722
|
+
series.filter(isBarSeries).forEach(function (seriesItem) {
|
|
723
|
+
seriesItem.dataset.data.forEach(function (value) {
|
|
724
|
+
const number = toNumber(value);
|
|
725
|
+
if (number !== null && number < 0) texts.push(formatValueText(number));
|
|
726
|
+
});
|
|
727
|
+
});
|
|
728
|
+
return texts;
|
|
729
|
+
};
|
|
730
|
+
|
|
731
|
+
// The room the values need around the plot. top, bottom: an upright bar chart. start, end: a chart that grows to
|
|
732
|
+
// the right. (end also: the last value of a line.)
|
|
733
|
+
const measureValueRooms = function (series) {
|
|
734
|
+
|
|
735
|
+
if (!basic.isOn(box.showValues)) return { top: 0, bottom: 0, start: 0, end: 0 };
|
|
736
|
+
|
|
737
|
+
const isSideways = (box.horizontal == 1);
|
|
738
|
+
const textHeight = getAxisTextHeight();
|
|
739
|
+
const gap = _s.axis.labelGap;
|
|
740
|
+
const hasUprightBarValues = (!isSideways && !isStacked() && series.some(isBarSeries));
|
|
741
|
+
const endTexts = getEndValueTexts(series);
|
|
742
|
+
const underBaseTexts = getUnderBaseTexts(series);
|
|
743
|
+
|
|
744
|
+
return {
|
|
745
|
+
top: (hasUprightBarValues) ? textHeight : 0,
|
|
746
|
+
bottom: (!isSideways && underBaseTexts.length) ? textHeight : 0,
|
|
747
|
+
start: (isSideways && underBaseTexts.length) ? Math.ceil(measureWidestText(underBaseTexts)) + gap : 0,
|
|
748
|
+
end: (endTexts.length) ? Math.ceil(measureWidestText(endTexts)) + gap : 0,
|
|
749
|
+
};
|
|
750
|
+
|
|
751
|
+
};
|
|
752
|
+
|
|
753
|
+
const getAxisTitleRooms = function () {
|
|
754
|
+
const room = getAxisTextHeight() + 2;
|
|
755
|
+
return { left: (box.yAxisText) ? room : 0, bottom: (box.xAxisText) ? room : 0 };
|
|
756
|
+
};
|
|
757
|
+
|
|
758
|
+
// WHY: A value over a fixed limit (maxValue: 100) must not draw over the title. A little room is left for the points.
|
|
759
|
+
const clipMarks = function (plot) {
|
|
760
|
+
const room = getPointRoom();
|
|
761
|
+
GraphBox._idCounter += 1;
|
|
762
|
+
const id = "graph-box-clip-" + GraphBox._idCounter;
|
|
763
|
+
const clip = addShape(definitions, "clipPath", { id: id });
|
|
764
|
+
addShape(clip, "rect", {
|
|
765
|
+
x: plot.left - room,
|
|
766
|
+
y: plot.top - room,
|
|
767
|
+
width: plot.right - plot.left + room * 2,
|
|
768
|
+
height: plot.bottom - plot.top + room * 2,
|
|
769
|
+
});
|
|
770
|
+
clipLayer.setAttribute("clip-path", "url(#" + id + ")");
|
|
771
|
+
overlayLayer.setAttribute("clip-path", "url(#" + id + ")");
|
|
772
|
+
};
|
|
773
|
+
|
|
774
|
+
// The small titles of the axes: at the edges of the chart.
|
|
775
|
+
const drawAxisTitles = function (plot, height) {
|
|
776
|
+
const textHeight = getAxisTextHeight();
|
|
777
|
+
if (box.xAxisText) {
|
|
778
|
+
addText(gridLayer, box.xAxisText, (plot.left + plot.right) / 2, height - textHeight / 2, "middle", colors.textColor);
|
|
779
|
+
}
|
|
780
|
+
if (box.yAxisText) {
|
|
781
|
+
const x = textHeight / 2;
|
|
782
|
+
const y = (plot.top + plot.bottom) / 2;
|
|
783
|
+
const title = addText(gridLayer, box.yAxisText, x, y, "middle", colors.textColor);
|
|
784
|
+
title.setAttribute("transform", "rotate(-90 " + x + " " + y + ")");
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
// THE AXES OF A LINE OR BAR CHART:
|
|
789
|
+
|
|
790
|
+
const getPointRoom = function () {
|
|
791
|
+
return _s.line.pointRadius + _s.line.pointRing + 1;
|
|
792
|
+
};
|
|
793
|
+
|
|
794
|
+
// The room of the texts around the plot, and the scale that fits it.
|
|
795
|
+
const measurePlot = function (limits, hasBands, indexCount, width, height, labelRoom) {
|
|
796
|
+
|
|
797
|
+
const labelGap = _s.axis.labelGap;
|
|
798
|
+
const pointRoom = getPointRoom();
|
|
799
|
+
const titleRooms = getAxisTitleRooms();
|
|
800
|
+
const top = Math.max(pointRoom, Math.ceil(_s.axis.fontSize / 2)) + limits.valueRooms.top;
|
|
801
|
+
const bottom = height - (labelRoom + labelGap + titleRooms.bottom + limits.valueRooms.bottom);
|
|
802
|
+
const scale = createValueScale(limits, bottom - top);
|
|
803
|
+
|
|
804
|
+
let left = titleRooms.left + Math.ceil(measureWidestText(scale.tickTexts)) + labelGap;
|
|
805
|
+
let right = width - Math.max(pointRoom, limits.valueRooms.end);
|
|
806
|
+
|
|
807
|
+
// WHY: Without bands the first and the last value are on the edges, so half of their labels is out of the plot.
|
|
808
|
+
if (!hasBands && indexCount > 0) {
|
|
809
|
+
left = Math.max(left, titleRooms.left + Math.ceil(measureAxisText(getLabelText(0)) / 2));
|
|
810
|
+
const lastLabelRoom = Math.ceil(measureAxisText(getLabelText(indexCount - 1)) / 2);
|
|
811
|
+
right = width - Math.max(pointRoom, lastLabelRoom, limits.valueRooms.end);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
return { left: left, top: top, right: Math.max(left + 1, right), bottom: Math.max(top + 1, bottom), scale: scale };
|
|
815
|
+
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
// Px between two places of the index axis
|
|
819
|
+
const measureSpacing = function (plot, hasBands, indexCount, isHorizontal) {
|
|
820
|
+
const indexLength = (isHorizontal) ? plot.bottom - plot.top : plot.right - plot.left;
|
|
821
|
+
return (hasBands) ? indexLength / indexCount : indexLength / Math.max(1, indexCount - 1);
|
|
822
|
+
};
|
|
823
|
+
|
|
824
|
+
const getLabelTexts = function (indexCount) {
|
|
825
|
+
const labelTexts = [];
|
|
826
|
+
for (let index = 0; index < indexCount; index++) labelTexts.push(getLabelText(index));
|
|
827
|
+
return labelTexts;
|
|
828
|
+
};
|
|
829
|
+
|
|
830
|
+
// maxLabels: the step that leaves at most that many labels.
|
|
831
|
+
const getMinLabelStep = function (indexCount) {
|
|
832
|
+
const maxLabels = toNumber(box.maxLabels) || 0;
|
|
833
|
+
return (maxLabels > 0) ? Math.max(1, Math.ceil(indexCount / maxLabels)) : 1;
|
|
834
|
+
};
|
|
835
|
+
|
|
836
|
+
// How the labels of the index axis are written: { texts, step, angle, room }
|
|
837
|
+
// WHY: A label that has no room is skipped on a line chart: it is time, the reader can follow it. A bar chart needs
|
|
838
|
+
// the name of every bar, so its labels turn, while each one still has a line of its own.
|
|
839
|
+
const planIndexLabels = function (hasBands, indexCount, spacing, height) {
|
|
840
|
+
|
|
841
|
+
const texts = getLabelTexts(indexCount);
|
|
842
|
+
const textHeight = getAxisTextHeight();
|
|
843
|
+
const needed = measureWidestText(texts) + _s.axis.labelSpace;
|
|
844
|
+
const angle = _s.axis.labelAngle;
|
|
845
|
+
const minStep = getMinLabelStep(indexCount);
|
|
846
|
+
|
|
847
|
+
if (needed <= spacing * minStep) return { texts: texts, step: minStep, angle: 0, room: textHeight };
|
|
848
|
+
|
|
849
|
+
if (!hasBands || !angle || spacing < textHeight) {
|
|
850
|
+
const step = Math.max(minStep, Math.ceil(needed / Math.max(1, spacing)));
|
|
851
|
+
return { texts: texts, step: step, angle: 0, room: textHeight };
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
const radians = angle * Math.PI / 180;
|
|
855
|
+
const maxWidth = height * _s.axis.maxLabelShare / Math.sin(radians);
|
|
856
|
+
const shortTexts = texts.map(function (text) {
|
|
857
|
+
return GraphBox.fitText(text, maxWidth, _s.axis.fontSize, _s.axis.fontFamily);
|
|
858
|
+
});
|
|
859
|
+
const room = Math.ceil(measureWidestText(shortTexts) * Math.sin(radians) + textHeight * Math.cos(radians));
|
|
860
|
+
return { texts: shortTexts, step: minStep, angle: angle, room: room };
|
|
861
|
+
|
|
862
|
+
};
|
|
863
|
+
|
|
864
|
+
// WHY: The room at the right was measured from the values, before the numbers of the axis were known. The last number
|
|
865
|
+
// stands in the middle of the end of the plot, so half of it must stay in the box: "2.25K" is wider than "2.1K".
|
|
866
|
+
const getRightOfLastTick = function (scale, width) {
|
|
867
|
+
const lastText = scale.tickTexts[scale.tickTexts.length - 1] || "";
|
|
868
|
+
return width - Math.ceil(measureAxisText(lastText) / 2);
|
|
869
|
+
};
|
|
870
|
+
|
|
871
|
+
// horizontal: 1: the labels are at the left, and the texts of the values under the plot.
|
|
872
|
+
const measureSidewaysPlot = function (limits, hasBands, indexCount, width, height) {
|
|
873
|
+
|
|
874
|
+
const labelGap = _s.axis.labelGap;
|
|
875
|
+
const textHeight = getAxisTextHeight();
|
|
876
|
+
const pointRoom = getPointRoom();
|
|
877
|
+
const maxLabelWidth = width * _s.axis.maxSideLabelShare;
|
|
878
|
+
const labelWidth = Math.min(maxLabelWidth, measureWidestText(getLabelTexts(indexCount)));
|
|
879
|
+
const tickWidth = measureWidestText([formatTickText(limits.low, 0), formatTickText(limits.high, 0)]);
|
|
880
|
+
const titleRooms = getAxisTitleRooms();
|
|
881
|
+
|
|
882
|
+
const left = titleRooms.left + Math.ceil(labelWidth) + labelGap + limits.valueRooms.start;
|
|
883
|
+
const right = Math.max(left + 1, width - Math.max(pointRoom, Math.ceil(tickWidth / 2), limits.valueRooms.end));
|
|
884
|
+
const top = (hasBands) ? 0 : Math.max(pointRoom, Math.ceil(textHeight / 2));
|
|
885
|
+
const bottom = Math.max(top + 1, height - (textHeight + labelGap + titleRooms.bottom));
|
|
886
|
+
const tickSpace = Math.max(_s.axis.sideTickSpace, tickWidth + _s.axis.labelSpace);
|
|
887
|
+
|
|
888
|
+
const scale = createValueScale(limits, right - left, tickSpace);
|
|
889
|
+
const lastRight = Math.min(right, getRightOfLastTick(scale, width));
|
|
890
|
+
return { left: left, top: top, right: Math.max(left + 1, lastRight), bottom: bottom, maxLabelWidth: maxLabelWidth, scale: scale };
|
|
891
|
+
|
|
892
|
+
};
|
|
893
|
+
|
|
894
|
+
// The labels at the left of the plot: { texts, step, angle, room }. Only a step: a text can not be high.
|
|
895
|
+
const planSideLabels = function (indexCount, spacing, maxLabelWidth) {
|
|
896
|
+
const texts = getLabelTexts(indexCount).map(function (text) {
|
|
897
|
+
return GraphBox.fitText(text, maxLabelWidth, _s.axis.fontSize, _s.axis.fontFamily);
|
|
898
|
+
});
|
|
899
|
+
const step = Math.max(getMinLabelStep(indexCount), Math.ceil(getAxisTextHeight() / Math.max(1, spacing)));
|
|
900
|
+
return { texts: texts, step: step, angle: 0, room: 0 };
|
|
901
|
+
};
|
|
902
|
+
|
|
903
|
+
const planUprightPlot = function (limits, hasBands, indexCount, width, height) {
|
|
904
|
+
|
|
905
|
+
const flatRoom = getAxisTextHeight();
|
|
906
|
+
const firstPlot = measurePlot(limits, hasBands, indexCount, width, height, flatRoom);
|
|
907
|
+
const labelPlan = planIndexLabels(hasBands, indexCount, measureSpacing(firstPlot, hasBands, indexCount, 0), height);
|
|
908
|
+
|
|
909
|
+
// WHY again: Turned labels need more room under the plot, so the plot and its scale change.
|
|
910
|
+
const hasMoreRoom = (labelPlan.room !== flatRoom);
|
|
911
|
+
const plot = (hasMoreRoom) ? measurePlot(limits, hasBands, indexCount, width, height, labelPlan.room) : firstPlot;
|
|
912
|
+
return { plot: plot, labelPlan: labelPlan };
|
|
913
|
+
|
|
914
|
+
};
|
|
915
|
+
|
|
916
|
+
const planSidewaysPlot = function (limits, hasBands, indexCount, width, height) {
|
|
917
|
+
const plot = measureSidewaysPlot(limits, hasBands, indexCount, width, height);
|
|
918
|
+
const spacing = measureSpacing(plot, hasBands, indexCount, 1);
|
|
919
|
+
return { plot: plot, labelPlan: planSideLabels(indexCount, spacing, plot.maxLabelWidth) };
|
|
920
|
+
};
|
|
921
|
+
|
|
922
|
+
const createAxes = function (series, limits, indexCount, width, height) {
|
|
923
|
+
|
|
924
|
+
const hasBands = series.some(isBarSeries);
|
|
925
|
+
const isHorizontal = (box.horizontal == 1);
|
|
926
|
+
const planner = (isHorizontal) ? planSidewaysPlot : planUprightPlot;
|
|
927
|
+
const plan = planner(limits, hasBands, indexCount, width, height);
|
|
928
|
+
const plot = plan.plot;
|
|
929
|
+
const scale = plot.scale;
|
|
930
|
+
const spacing = measureSpacing(plot, hasBands, indexCount, isHorizontal);
|
|
931
|
+
const indexStart = (isHorizontal) ? plot.top : plot.left;
|
|
932
|
+
const indexLength = (isHorizontal) ? plot.bottom - plot.top : plot.right - plot.left;
|
|
933
|
+
const scaleSpan = (scale.max - scale.min) || 1;
|
|
934
|
+
|
|
935
|
+
const axes = {
|
|
936
|
+
isHorizontal: isHorizontal,
|
|
937
|
+
hasBands: hasBands,
|
|
938
|
+
indexCount: indexCount,
|
|
939
|
+
spacing: spacing,
|
|
940
|
+
plot: plot,
|
|
941
|
+
scale: scale,
|
|
942
|
+
labelPlan: plan.labelPlan,
|
|
943
|
+
valueRooms: limits.valueRooms,
|
|
944
|
+
};
|
|
945
|
+
|
|
946
|
+
axes.toIndexPosition = function (index) {
|
|
947
|
+
if (hasBands) return indexStart + spacing * (index + 0.5);
|
|
948
|
+
if (indexCount === 1) return indexStart + indexLength / 2;
|
|
949
|
+
return indexStart + spacing * index;
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
axes.toValuePosition = function (value) {
|
|
953
|
+
const share = (value - scale.min) / scaleSpan;
|
|
954
|
+
if (isHorizontal) return plot.left + share * (plot.right - plot.left);
|
|
955
|
+
return plot.bottom - share * (plot.bottom - plot.top);
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
// A point from its places on the two axes.
|
|
959
|
+
axes.joinPositions = function (indexPosition, valuePosition) {
|
|
960
|
+
if (isHorizontal) return { x: valuePosition, y: indexPosition };
|
|
961
|
+
return { x: indexPosition, y: valuePosition };
|
|
962
|
+
};
|
|
963
|
+
|
|
964
|
+
axes.toPoint = function (index, value) {
|
|
965
|
+
return axes.joinPositions(axes.toIndexPosition(index), axes.toValuePosition(value));
|
|
966
|
+
};
|
|
967
|
+
|
|
968
|
+
axes.toIndex = function (x, y) {
|
|
969
|
+
const position = (isHorizontal) ? y : x;
|
|
970
|
+
const place = (position - indexStart) / spacing;
|
|
971
|
+
const index = (hasBands) ? Math.floor(place) : Math.round(place);
|
|
972
|
+
return Math.min(indexCount - 1, Math.max(0, index));
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
axes.baseValue = getBaseValue(scale);
|
|
976
|
+
|
|
977
|
+
axes.isInsidePlot = function (x, y) {
|
|
978
|
+
const room = _s.axis.labelGap;
|
|
979
|
+
return (x >= plot.left - room && x <= plot.right + room && y >= plot.top - room && y <= plot.bottom + room);
|
|
980
|
+
};
|
|
981
|
+
|
|
982
|
+
return axes;
|
|
983
|
+
|
|
984
|
+
};
|
|
985
|
+
|
|
986
|
+
// A line of the value axis: across the plot.
|
|
987
|
+
const addValueLine = function (axes, position, color) {
|
|
988
|
+
const plot = axes.plot;
|
|
989
|
+
if (axes.isHorizontal) return addLine(gridLayer, position, plot.top, position, plot.bottom, color);
|
|
990
|
+
return addLine(gridLayer, plot.left, position, plot.right, position, color);
|
|
991
|
+
};
|
|
992
|
+
|
|
993
|
+
const addTickText = function (axes, text, position) {
|
|
994
|
+
if (axes.isHorizontal) {
|
|
995
|
+
addText(gridLayer, text, position, axes.plot.bottom + _s.axis.labelGap + getAxisTextHeight() / 2);
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
addText(gridLayer, text, axes.plot.left - _s.axis.labelGap, position, "end");
|
|
999
|
+
};
|
|
1000
|
+
|
|
1001
|
+
const drawValueAxis = function (axes) {
|
|
1002
|
+
|
|
1003
|
+
axes.scale.ticks.forEach(function (tick, tickIndex) {
|
|
1004
|
+
const position = toPixelCenter(axes.toValuePosition(tick));
|
|
1005
|
+
addValueLine(axes, position, colors.gridColor);
|
|
1006
|
+
addTickText(axes, axes.scale.tickTexts[tickIndex], position);
|
|
1007
|
+
});
|
|
1008
|
+
|
|
1009
|
+
addValueLine(axes, toPixelCenter(axes.toValuePosition(axes.baseValue)), colors.axisColor);
|
|
1010
|
+
|
|
1011
|
+
};
|
|
1012
|
+
|
|
1013
|
+
const drawSideLabels = function (axes) {
|
|
1014
|
+
const plan = axes.labelPlan;
|
|
1015
|
+
const x = axes.plot.left - _s.axis.labelGap - axes.valueRooms.start;
|
|
1016
|
+
for (let index = 0; index < axes.indexCount; index += plan.step) {
|
|
1017
|
+
addText(gridLayer, plan.texts[index], x, axes.toIndexPosition(index), "end");
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
const drawIndexLabels = function (axes) {
|
|
1022
|
+
|
|
1023
|
+
if (axes.isHorizontal) {
|
|
1024
|
+
drawSideLabels(axes);
|
|
1025
|
+
return;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
const plan = axes.labelPlan;
|
|
1029
|
+
const labelTop = axes.plot.bottom + axes.valueRooms.bottom + _s.axis.labelGap;
|
|
1030
|
+
const flatY = labelTop + getAxisTextHeight() / 2;
|
|
1031
|
+
const turnedY = labelTop;
|
|
1032
|
+
|
|
1033
|
+
for (let index = 0; index < axes.indexCount; index += plan.step) {
|
|
1034
|
+
const x = axes.toIndexPosition(index);
|
|
1035
|
+
if (!plan.angle) {
|
|
1036
|
+
addText(gridLayer, plan.texts[index], x, flatY);
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
// A turned label ends under its bar.
|
|
1040
|
+
const label = addText(gridLayer, plan.texts[index], x, turnedY, "end");
|
|
1041
|
+
label.setAttribute("transform", "rotate(" + (-plan.angle) + " " + x + " " + turnedY + ")");
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
};
|
|
1045
|
+
|
|
1046
|
+
// THE BARS:
|
|
1047
|
+
|
|
1048
|
+
const getBarThickness = function (axes, slotCount) {
|
|
1049
|
+
const free = axes.spacing * _s.bar.bandShare - _s.bar.gap * (slotCount - 1);
|
|
1050
|
+
return Math.max(1, Math.min(_s.bar.maxThickness, free / slotCount));
|
|
1051
|
+
};
|
|
1052
|
+
|
|
1053
|
+
// The base and the end of a bar on the value axis.
|
|
1054
|
+
const getBarEnds = function (range, axes) {
|
|
1055
|
+
|
|
1056
|
+
const scale = axes.scale;
|
|
1057
|
+
const endPosition = axes.toValuePosition(Math.min(scale.max, Math.max(scale.min, range.to)));
|
|
1058
|
+
let basePosition = axes.toValuePosition(Math.min(scale.max, Math.max(scale.min, range.from)));
|
|
1059
|
+
const direction = Math.sign(endPosition - basePosition);
|
|
1060
|
+
|
|
1061
|
+
// WHY: The gap is in the geometry, not a line in the color of the box, so a box with no color has it too.
|
|
1062
|
+
if (range.from !== 0) basePosition += direction * _s.bar.gap;
|
|
1063
|
+
|
|
1064
|
+
// WHY: A very small value is still there: it does not vanish, or turn over after the gap.
|
|
1065
|
+
const isTurnedOver = (Math.sign(endPosition - basePosition) !== direction);
|
|
1066
|
+
const isTooShort = (Math.abs(endPosition - basePosition) < _s.bar.minLength);
|
|
1067
|
+
if (isTurnedOver || isTooShort) basePosition = endPosition - direction * _s.bar.minLength;
|
|
1068
|
+
|
|
1069
|
+
return { basePosition: basePosition, endPosition: endPosition };
|
|
1070
|
+
|
|
1071
|
+
};
|
|
1072
|
+
|
|
1073
|
+
const createBarRect = function (range, slotStart, thickness, axes) {
|
|
1074
|
+
const ends = getBarEnds(range, axes);
|
|
1075
|
+
const start = Math.min(ends.basePosition, ends.endPosition);
|
|
1076
|
+
const barLength = Math.abs(ends.endPosition - ends.basePosition);
|
|
1077
|
+
if (axes.isHorizontal) return { left: start, top: slotStart, width: barLength, height: thickness };
|
|
1078
|
+
return { left: slotStart, top: start, width: thickness, height: barLength };
|
|
1079
|
+
};
|
|
1080
|
+
|
|
1081
|
+
const getRoundSide = function (range, axes) {
|
|
1082
|
+
const isGoingUp = (range.to >= range.from);
|
|
1083
|
+
if (axes.isHorizontal) return (isGoingUp) ? "right" : "left";
|
|
1084
|
+
return (isGoingUp) ? "top" : "bottom";
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
// Is it the last value of its stack on its side of the base line? Only that one has round corners.
|
|
1088
|
+
const isOuterValue = function (barSeries, seriesPlace, index, range) {
|
|
1089
|
+
const isOverBase = (range.to >= range.from);
|
|
1090
|
+
for (let place = seriesPlace + 1; place < barSeries.length; place++) {
|
|
1091
|
+
const laterRange = barSeries[place].ranges[index];
|
|
1092
|
+
if (!laterRange || laterRange.from === laterRange.to) continue;
|
|
1093
|
+
if ((laterRange.to >= laterRange.from) === isOverBase) return false;
|
|
1094
|
+
}
|
|
1095
|
+
return true;
|
|
1096
|
+
};
|
|
1097
|
+
|
|
1098
|
+
// A value in a part of a stack, only when it fits: nothing is cut. Its color comes from the color of the part.
|
|
1099
|
+
const drawStackValue = function (seriesItem, index, rect) {
|
|
1100
|
+
const text = formatValueText(getValue(seriesItem.dataset, index));
|
|
1101
|
+
const roomWidth = rect.width - _s.values.sidePadding * 2;
|
|
1102
|
+
const roomHeight = rect.height - _s.values.sidePadding * 2;
|
|
1103
|
+
if (measureAxisText(text) > roomWidth || _s.axis.fontSize > roomHeight) return;
|
|
1104
|
+
const color = GraphBox.getTextColorOn(getMarkColor(seriesItem, index));
|
|
1105
|
+
const label = addText(valueLayer, text, rect.left + rect.width / 2, rect.top + rect.height / 2, "middle", color);
|
|
1106
|
+
label.setAttribute("font-family", "opensans-bold");
|
|
1107
|
+
};
|
|
1108
|
+
|
|
1109
|
+
// A value after the end of its bar, only when it fits in the place of the bar.
|
|
1110
|
+
const drawBarValue = function (seriesItem, index, range, rect, slotLength, axes) {
|
|
1111
|
+
|
|
1112
|
+
const text = formatValueText(getValue(seriesItem.dataset, index));
|
|
1113
|
+
const isGoingUp = (range.to >= range.from);
|
|
1114
|
+
const gap = _s.values.gap;
|
|
1115
|
+
|
|
1116
|
+
if (axes.isHorizontal) {
|
|
1117
|
+
if (_s.axis.fontSize > slotLength) return;
|
|
1118
|
+
const x = (isGoingUp) ? rect.left + rect.width + gap : rect.left - gap;
|
|
1119
|
+
addText(valueLayer, text, x, rect.top + rect.height / 2, (isGoingUp) ? "start" : "end", colors.textColor);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
if (measureAxisText(text) > slotLength) return;
|
|
1124
|
+
const textMiddle = getAxisTextHeight() / 2 + gap;
|
|
1125
|
+
const y = (isGoingUp) ? rect.top - textMiddle : rect.top + rect.height + textMiddle;
|
|
1126
|
+
addText(valueLayer, text, rect.left + rect.width / 2, y, "middle", colors.textColor);
|
|
1127
|
+
|
|
1128
|
+
};
|
|
1129
|
+
|
|
1130
|
+
// A bar: its round corners are at the end of its value, its base is square.
|
|
1131
|
+
const drawBar = function (seriesItem, index, range, roundSide, slotStart, thickness, axes) {
|
|
1132
|
+
const rect = createBarRect(range, slotStart, thickness, axes);
|
|
1133
|
+
const shape = addShape(markLayer, "path", {
|
|
1134
|
+
d: GraphBox.barPath(rect, _s.bar.round, roundSide),
|
|
1135
|
+
fill: getMarkColor(seriesItem, index),
|
|
1136
|
+
});
|
|
1137
|
+
rememberMark("bar", getSeriesKeyOf(seriesItem), index, shape, { rect: rect });
|
|
1138
|
+
seriesItem.barRects[index] = rect;
|
|
1139
|
+
if (!basic.isOn(box.showValues)) return;
|
|
1140
|
+
if (isStacked()) {
|
|
1141
|
+
drawStackValue(seriesItem, index, rect);
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
const slotCount = seriesItem.slotCount;
|
|
1145
|
+
const slotLength = (slotCount > 1) ? thickness + _s.bar.gap : axes.spacing;
|
|
1146
|
+
drawBarValue(seriesItem, index, range, rect, slotLength, axes);
|
|
1147
|
+
};
|
|
1148
|
+
|
|
1149
|
+
const drawBars = function (series, axes) {
|
|
1150
|
+
|
|
1151
|
+
const barSeries = series.filter(isBarSeries);
|
|
1152
|
+
if (!barSeries.length) return;
|
|
1153
|
+
|
|
1154
|
+
const isBarStacked = isStacked();
|
|
1155
|
+
const slotCount = (isBarStacked) ? 1 : barSeries.length;
|
|
1156
|
+
const thickness = getBarThickness(axes, slotCount);
|
|
1157
|
+
const groupLength = thickness * slotCount + _s.bar.gap * (slotCount - 1);
|
|
1158
|
+
|
|
1159
|
+
barSeries.forEach(function (seriesItem, seriesPlace) {
|
|
1160
|
+
const slot = (isBarStacked) ? 0 : seriesPlace;
|
|
1161
|
+
const slotOffset = slot * (thickness + _s.bar.gap) - groupLength / 2;
|
|
1162
|
+
seriesItem.barRects = [];
|
|
1163
|
+
seriesItem.slotCount = slotCount;
|
|
1164
|
+
seriesItem.ranges.forEach(function (range, index) {
|
|
1165
|
+
if (!range || range.from === range.to) return;
|
|
1166
|
+
const isRound = (!isBarStacked || isOuterValue(barSeries, seriesPlace, index, range));
|
|
1167
|
+
const roundSide = (isRound) ? getRoundSide(range, axes) : "";
|
|
1168
|
+
drawBar(seriesItem, index, range, roundSide, axes.toIndexPosition(index) + slotOffset, thickness, axes);
|
|
1169
|
+
});
|
|
1170
|
+
});
|
|
1171
|
+
|
|
1172
|
+
};
|
|
1173
|
+
|
|
1174
|
+
// THE LINES:
|
|
1175
|
+
|
|
1176
|
+
// The places with a value that follow each other: [[0, 1, 2], [5, 6]] (a line breaks at an empty place)
|
|
1177
|
+
const getSegments = function (seriesItem) {
|
|
1178
|
+
const segments = [];
|
|
1179
|
+
let segment = null;
|
|
1180
|
+
seriesItem.ranges.forEach(function (range, index) {
|
|
1181
|
+
if (!range) {
|
|
1182
|
+
segment = null;
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
if (!segment) {
|
|
1186
|
+
segment = [];
|
|
1187
|
+
segments.push(segment);
|
|
1188
|
+
}
|
|
1189
|
+
segment.push(index);
|
|
1190
|
+
});
|
|
1191
|
+
return segments;
|
|
1192
|
+
};
|
|
1193
|
+
|
|
1194
|
+
const getDatasetCurve = function (dataset) {
|
|
1195
|
+
return dataset.curve || box.curve;
|
|
1196
|
+
};
|
|
1197
|
+
|
|
1198
|
+
const getFillType = function (dataset) {
|
|
1199
|
+
if (dataset.fill !== undefined) return dataset.fill;
|
|
1200
|
+
return (getDatasetType(dataset) === "area") ? 1 : 0;
|
|
1201
|
+
};
|
|
1202
|
+
|
|
1203
|
+
const addGradient = function (color) {
|
|
1204
|
+
GraphBox._idCounter += 1;
|
|
1205
|
+
const id = "graph-box-gradient-" + GraphBox._idCounter;
|
|
1206
|
+
const gradient = addShape(definitions, "linearGradient", { id: id, x1: 0, y1: 0, x2: 0, y2: 1 });
|
|
1207
|
+
addShape(gradient, "stop", { offset: 0, "stop-color": color, "stop-opacity": _s.line.gradientOpacity });
|
|
1208
|
+
addShape(gradient, "stop", { offset: 1, "stop-color": color, "stop-opacity": 0 });
|
|
1209
|
+
return "url(#" + id + ")";
|
|
1210
|
+
};
|
|
1211
|
+
|
|
1212
|
+
// Where an area ends: at 0 (stacked: on the one before it), or with fillTo: "start" at the start of the axis.
|
|
1213
|
+
const getAreaBaseValue = function (seriesItem, index, axes) {
|
|
1214
|
+
const scale = axes.scale;
|
|
1215
|
+
if (seriesItem.dataset.fillTo === "start") return scale.min;
|
|
1216
|
+
return Math.min(scale.max, Math.max(scale.min, seriesItem.ranges[index].from));
|
|
1217
|
+
};
|
|
1218
|
+
|
|
1219
|
+
const drawArea = function (seriesItem, segment, segmentPlace, axes) {
|
|
1220
|
+
|
|
1221
|
+
if (segment.length < 2) return;
|
|
1222
|
+
|
|
1223
|
+
const isSmooth = (getDatasetCurve(seriesItem.dataset) === "smooth");
|
|
1224
|
+
const fillType = getFillType(seriesItem.dataset);
|
|
1225
|
+
const isGradient = (fillType === "gradient");
|
|
1226
|
+
const upperPoints = segment.map(function (index) {
|
|
1227
|
+
return axes.toPoint(index, seriesItem.ranges[index].to);
|
|
1228
|
+
});
|
|
1229
|
+
const lowerPoints = segment.slice().reverse().map(function (index) {
|
|
1230
|
+
return axes.toPoint(index, getAreaBaseValue(seriesItem, index, axes));
|
|
1231
|
+
});
|
|
1232
|
+
|
|
1233
|
+
const shape = addShape(markLayer, "path", {
|
|
1234
|
+
d: "M" + GraphBox.pointText(upperPoints[0]) + GraphBox.curveCommands(upperPoints, isSmooth, axes.isHorizontal) +
|
|
1235
|
+
"L" + GraphBox.pointText(lowerPoints[0]) + GraphBox.curveCommands(lowerPoints, isSmooth, axes.isHorizontal) + "Z",
|
|
1236
|
+
fill: (isGradient) ? addGradient(seriesItem.color) : seriesItem.color,
|
|
1237
|
+
"fill-opacity": (isGradient) ? 1 : _s.line.fillOpacity,
|
|
1238
|
+
});
|
|
1239
|
+
rememberMark("area", getSeriesKeyOf(seriesItem), segmentPlace, shape);
|
|
1240
|
+
|
|
1241
|
+
};
|
|
1242
|
+
|
|
1243
|
+
const drawAreas = function (series, axes) {
|
|
1244
|
+
series.filter(isLineSeries).forEach(function (seriesItem) {
|
|
1245
|
+
if (!getFillType(seriesItem.dataset)) return;
|
|
1246
|
+
getSegments(seriesItem).forEach(function (segment, segmentPlace) {
|
|
1247
|
+
drawArea(seriesItem, segment, segmentPlace, axes);
|
|
1248
|
+
});
|
|
1249
|
+
});
|
|
1250
|
+
};
|
|
1251
|
+
|
|
1252
|
+
const isPointsShown = function (seriesItem, axes) {
|
|
1253
|
+
const showPoints = (seriesItem.dataset.showPoints !== undefined) ? seriesItem.dataset.showPoints : box.showPoints;
|
|
1254
|
+
if (showPoints !== "auto") return basic.isOn(showPoints);
|
|
1255
|
+
return (axes.spacing >= _s.line.pointSpace && !seriesItem.dataset.dashed);
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
// WHY twice the ring, under the fill: A line of a circle is half inside it. So the point keeps its size, and the
|
|
1259
|
+
// ring is out of it.
|
|
1260
|
+
const addPoint = function (layer, point, color, radius) {
|
|
1261
|
+
return addShape(layer, "circle", {
|
|
1262
|
+
cx: point.x,
|
|
1263
|
+
cy: point.y,
|
|
1264
|
+
r: radius,
|
|
1265
|
+
fill: color,
|
|
1266
|
+
stroke: getSurfaceColor(),
|
|
1267
|
+
"stroke-width": _s.line.pointRing * 2,
|
|
1268
|
+
"paint-order": "stroke",
|
|
1269
|
+
});
|
|
1270
|
+
};
|
|
1271
|
+
|
|
1272
|
+
const drawLineSeries = function (seriesItem, axes) {
|
|
1273
|
+
|
|
1274
|
+
const isSmooth = (getDatasetCurve(seriesItem.dataset) === "smooth");
|
|
1275
|
+
const hasPoints = isPointsShown(seriesItem, axes);
|
|
1276
|
+
|
|
1277
|
+
seriesItem.points = [];
|
|
1278
|
+
|
|
1279
|
+
const seriesKey = getSeriesKeyOf(seriesItem);
|
|
1280
|
+
|
|
1281
|
+
getSegments(seriesItem).forEach(function (segment, segmentPlace) {
|
|
1282
|
+
|
|
1283
|
+
const points = segment.map(function (index) {
|
|
1284
|
+
const point = axes.toPoint(index, seriesItem.ranges[index].to);
|
|
1285
|
+
seriesItem.points[index] = point;
|
|
1286
|
+
return point;
|
|
1287
|
+
});
|
|
1288
|
+
|
|
1289
|
+
const line = addShape(markLayer, "path", {
|
|
1290
|
+
d: "M" + GraphBox.pointText(points[0]) + GraphBox.curveCommands(points, isSmooth, axes.isHorizontal),
|
|
1291
|
+
fill: "none",
|
|
1292
|
+
stroke: seriesItem.color,
|
|
1293
|
+
"stroke-width": _s.line.width,
|
|
1294
|
+
"stroke-linecap": "round",
|
|
1295
|
+
"stroke-linejoin": "round",
|
|
1296
|
+
"stroke-dasharray": (seriesItem.dataset.dashed) ? _s.line.dash : "none",
|
|
1297
|
+
});
|
|
1298
|
+
rememberMark("line", seriesKey, segmentPlace, line);
|
|
1299
|
+
|
|
1300
|
+
// WHY the lone value: It has no line, so without a point it would not be seen.
|
|
1301
|
+
if (hasPoints || points.length === 1) {
|
|
1302
|
+
points.forEach(function (point, pointPlace) {
|
|
1303
|
+
const dot = addPoint(markLayer, point, seriesItem.color, _s.line.pointRadius);
|
|
1304
|
+
rememberMark("point", seriesKey, segment[pointPlace], dot, { point: point, isOnLine: 1 });
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
});
|
|
1309
|
+
|
|
1310
|
+
};
|
|
1311
|
+
|
|
1312
|
+
// The last value of every line. WHY only the last: A number on every point can not be read.
|
|
1313
|
+
// WHY skipped: Two lines that end at the same place would write over each other. The legend still names them.
|
|
1314
|
+
const drawLineEndValues = function (series, axes) {
|
|
1315
|
+
|
|
1316
|
+
if (!basic.isOn(box.showValues) || axes.isHorizontal) return;
|
|
1317
|
+
|
|
1318
|
+
const usedPlaces = [];
|
|
1319
|
+
const textHeight = getAxisTextHeight();
|
|
1320
|
+
|
|
1321
|
+
series.filter(isLineSeries).forEach(function (seriesItem) {
|
|
1322
|
+
const lastPoint = seriesItem.points[seriesItem.points.length - 1];
|
|
1323
|
+
if (!lastPoint) return;
|
|
1324
|
+
const isFree = usedPlaces.every(function (y) { return Math.abs(y - lastPoint.y) >= textHeight; });
|
|
1325
|
+
if (!isFree) return;
|
|
1326
|
+
usedPlaces.push(lastPoint.y);
|
|
1327
|
+
const text = formatValueText(getLastValue(seriesItem));
|
|
1328
|
+
addText(valueLayer, text, lastPoint.x + _s.axis.labelGap, lastPoint.y, "start", colors.textColor);
|
|
1329
|
+
});
|
|
1330
|
+
|
|
1331
|
+
};
|
|
1332
|
+
|
|
1333
|
+
const drawLines = function (series, axes) {
|
|
1334
|
+
series.filter(isLineSeries).forEach(function (seriesItem) {
|
|
1335
|
+
drawLineSeries(seriesItem, axes);
|
|
1336
|
+
});
|
|
1337
|
+
drawLineEndValues(series, axes);
|
|
1338
|
+
};
|
|
1339
|
+
|
|
1340
|
+
// THE ACTIVE ITEM OF A LINE OR BAR CHART:
|
|
1341
|
+
|
|
1342
|
+
const getDistanceToRect = function (rect, x, y) {
|
|
1343
|
+
const distanceX = Math.max(rect.left - x, 0, x - rect.left - rect.width);
|
|
1344
|
+
const distanceY = Math.max(rect.top - y, 0, y - rect.top - rect.height);
|
|
1345
|
+
return Math.hypot(distanceX, distanceY);
|
|
1346
|
+
};
|
|
1347
|
+
|
|
1348
|
+
const getDistanceToMark = function (seriesItem, index, x, y) {
|
|
1349
|
+
if (isBarSeries(seriesItem)) {
|
|
1350
|
+
const rect = seriesItem.barRects && seriesItem.barRects[index];
|
|
1351
|
+
return (rect) ? getDistanceToRect(rect, x, y) : Infinity;
|
|
1352
|
+
}
|
|
1353
|
+
const point = seriesItem.points && seriesItem.points[index];
|
|
1354
|
+
return (point) ? Math.hypot(point.x - x, point.y - y) : Infinity;
|
|
1355
|
+
};
|
|
1356
|
+
|
|
1357
|
+
const findNearestDataset = function (series, index, x, y) {
|
|
1358
|
+
let nearestDistance = Infinity;
|
|
1359
|
+
let datasetIndex = null;
|
|
1360
|
+
series.forEach(function (seriesItem) {
|
|
1361
|
+
const distance = getDistanceToMark(seriesItem, index, x, y);
|
|
1362
|
+
if (distance >= nearestDistance) return;
|
|
1363
|
+
nearestDistance = distance;
|
|
1364
|
+
datasetIndex = seriesItem.datasetIndex;
|
|
1365
|
+
});
|
|
1366
|
+
return datasetIndex;
|
|
1367
|
+
};
|
|
1368
|
+
|
|
1369
|
+
const paintBandWash = function (axes, index) {
|
|
1370
|
+
const plot = axes.plot;
|
|
1371
|
+
const bandStart = axes.toIndexPosition(index) - axes.spacing / 2;
|
|
1372
|
+
const shape = (axes.isHorizontal)
|
|
1373
|
+
? { x: plot.left, y: bandStart, width: plot.right - plot.left, height: axes.spacing }
|
|
1374
|
+
: { x: bandStart, y: plot.top, width: axes.spacing, height: plot.bottom - plot.top };
|
|
1375
|
+
shape.fill = colors.hoverColor;
|
|
1376
|
+
addShape(washLayer, "rect", shape);
|
|
1377
|
+
};
|
|
1378
|
+
|
|
1379
|
+
const paintCrosshair = function (axes, index) {
|
|
1380
|
+
const plot = axes.plot;
|
|
1381
|
+
const position = toPixelCenter(axes.toIndexPosition(index));
|
|
1382
|
+
if (axes.isHorizontal) {
|
|
1383
|
+
addLine(washLayer, plot.left, position, plot.right, position, colors.axisColor);
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
addLine(washLayer, position, plot.top, position, plot.bottom, colors.axisColor);
|
|
1387
|
+
};
|
|
1388
|
+
|
|
1389
|
+
const paintActivePoints = function (series, index) {
|
|
1390
|
+
series.filter(isLineSeries).forEach(function (seriesItem) {
|
|
1391
|
+
const point = seriesItem.points[index];
|
|
1392
|
+
if (point) addPoint(overlayLayer, point, seriesItem.color, _s.line.pointRadius + 1);
|
|
1393
|
+
});
|
|
1394
|
+
};
|
|
1395
|
+
|
|
1396
|
+
const addTargetRows = function (rows) {
|
|
1397
|
+
if (box.type === "radar") return;
|
|
1398
|
+
getTargetLines().forEach(function (line) {
|
|
1399
|
+
rows.push({ color: getTargetColor(line), valueText: formatValueText(toNumber(line.value)), nameText: line.label || "" });
|
|
1400
|
+
});
|
|
1401
|
+
};
|
|
1402
|
+
|
|
1403
|
+
// The tooltip of one place: every series at that place.
|
|
1404
|
+
const getPlaceReadout = function (series, index) {
|
|
1405
|
+
const rows = [];
|
|
1406
|
+
let total = 0;
|
|
1407
|
+
series.forEach(function (seriesItem) {
|
|
1408
|
+
const value = getValue(seriesItem.dataset, index);
|
|
1409
|
+
if (value === null) return;
|
|
1410
|
+
total += value;
|
|
1411
|
+
rows.push({
|
|
1412
|
+
color: getMarkColor(seriesItem, index),
|
|
1413
|
+
valueText: formatValueText(value),
|
|
1414
|
+
nameText: seriesItem.dataset.label || "",
|
|
1415
|
+
});
|
|
1416
|
+
});
|
|
1417
|
+
if (isStacked() && box.totalText && rows.length > 1) {
|
|
1418
|
+
rows.push({ color: "transparent", valueText: formatValueText(total), nameText: box.totalText });
|
|
1419
|
+
}
|
|
1420
|
+
if (rows.length) addTargetRows(rows);
|
|
1421
|
+
return { titleText: getLabelText(index), rows: rows };
|
|
1422
|
+
};
|
|
1423
|
+
|
|
1424
|
+
// For the keyboard: at the end of the longest value at that place.
|
|
1425
|
+
const getCartesianAnchor = function (series, axes, index) {
|
|
1426
|
+
const nearestEnd = (axes.isHorizontal) ? Math.max : Math.min;
|
|
1427
|
+
let valuePosition = axes.toValuePosition(axes.baseValue);
|
|
1428
|
+
series.forEach(function (seriesItem) {
|
|
1429
|
+
const range = seriesItem.ranges[index];
|
|
1430
|
+
if (range) valuePosition = nearestEnd(valuePosition, axes.toValuePosition(range.to));
|
|
1431
|
+
});
|
|
1432
|
+
return axes.joinPositions(axes.toIndexPosition(index), valuePosition);
|
|
1433
|
+
};
|
|
1434
|
+
|
|
1435
|
+
const createCartesianView = function (series, axes) {
|
|
1436
|
+
return {
|
|
1437
|
+
findItem: function (x, y) {
|
|
1438
|
+
if (!axes.isInsidePlot(x, y)) return null;
|
|
1439
|
+
const index = axes.toIndex(x, y);
|
|
1440
|
+
return { index: index, datasetIndex: findNearestDataset(series, index, x, y) };
|
|
1441
|
+
},
|
|
1442
|
+
stepItem: function (item, step) {
|
|
1443
|
+
if (!item) return { index: 0, datasetIndex: null };
|
|
1444
|
+
const index = Math.min(axes.indexCount - 1, Math.max(0, item.index + step));
|
|
1445
|
+
return { index: index, datasetIndex: null };
|
|
1446
|
+
},
|
|
1447
|
+
hasItem: function (item) {
|
|
1448
|
+
return (item.index < axes.indexCount);
|
|
1449
|
+
},
|
|
1450
|
+
paintItem: function (item) {
|
|
1451
|
+
if (axes.hasBands) paintBandWash(axes, item.index);
|
|
1452
|
+
else paintCrosshair(axes, item.index);
|
|
1453
|
+
paintActivePoints(series, item.index);
|
|
1454
|
+
},
|
|
1455
|
+
getReadout: function (item) {
|
|
1456
|
+
return getPlaceReadout(series, item.index);
|
|
1457
|
+
},
|
|
1458
|
+
getAnchor: function (item) {
|
|
1459
|
+
return getCartesianAnchor(series, axes, item.index);
|
|
1460
|
+
},
|
|
1461
|
+
};
|
|
1462
|
+
};
|
|
1463
|
+
|
|
1464
|
+
const drawCartesian = function (width, height) {
|
|
1465
|
+
|
|
1466
|
+
const series = getVisibleSeries();
|
|
1467
|
+
const indexCount = getIndexCount(series);
|
|
1468
|
+
addValueRanges(series, indexCount);
|
|
1469
|
+
|
|
1470
|
+
const limits = getValueLimits(series);
|
|
1471
|
+
if (!limits) return null;
|
|
1472
|
+
limits.valueRooms = measureValueRooms(series);
|
|
1473
|
+
|
|
1474
|
+
const axes = createAxes(series, limits, indexCount, width, height);
|
|
1475
|
+
drawnAxes = axes;
|
|
1476
|
+
|
|
1477
|
+
clipMarks(axes.plot);
|
|
1478
|
+
drawValueAxis(axes);
|
|
1479
|
+
drawIndexLabels(axes);
|
|
1480
|
+
drawAxisTitles(axes.plot, height);
|
|
1481
|
+
drawAreas(series, axes);
|
|
1482
|
+
drawBars(series, axes);
|
|
1483
|
+
drawLines(series, axes);
|
|
1484
|
+
drawTargetLines(axes.plot, axes.scale, axes.toValuePosition, axes.isHorizontal);
|
|
1485
|
+
|
|
1486
|
+
return createCartesianView(series, axes);
|
|
1487
|
+
|
|
1488
|
+
};
|
|
1489
|
+
|
|
1490
|
+
// THE PIE AND THE DOUGHNUT:
|
|
1491
|
+
|
|
1492
|
+
const isPieType = function () {
|
|
1493
|
+
return (box.type === "pie" || box.type === "doughnut");
|
|
1494
|
+
};
|
|
1495
|
+
|
|
1496
|
+
const getSliceKey = function (index) {
|
|
1497
|
+
if (index === GraphBox.OTHER_SLICE) return "#other";
|
|
1498
|
+
return getLabelText(index) || ("#" + index);
|
|
1499
|
+
};
|
|
1500
|
+
|
|
1501
|
+
const getSliceName = function (index) {
|
|
1502
|
+
return (index === GraphBox.OTHER_SLICE) ? box.otherText : getLabelText(index);
|
|
1503
|
+
};
|
|
1504
|
+
|
|
1505
|
+
const getSliceCount = function (dataset) {
|
|
1506
|
+
return Math.max(box.data.labels.length, dataset.data.length);
|
|
1507
|
+
};
|
|
1508
|
+
|
|
1509
|
+
// Every place of the first dataset that has a value: { index, value }. (A slice can not be less than nothing.)
|
|
1510
|
+
const getValuedSlices = function () {
|
|
1511
|
+
const dataset = box.data.datasets[0];
|
|
1512
|
+
const slices = [];
|
|
1513
|
+
if (!dataset) return slices;
|
|
1514
|
+
for (let index = 0; index < getSliceCount(dataset); index++) {
|
|
1515
|
+
const value = getValue(dataset, index);
|
|
1516
|
+
if (value > 0) slices.push({ index: index, value: value });
|
|
1517
|
+
}
|
|
1518
|
+
return slices;
|
|
1519
|
+
};
|
|
1520
|
+
|
|
1521
|
+
// The slices that stay alone, and the smallest ones that are drawn as one: { kept, folded }. Each keeps its place.
|
|
1522
|
+
// WHY not from the visible slices: Hiding a slice with the legend must not change the other slices.
|
|
1523
|
+
const splitSlices = function () {
|
|
1524
|
+
|
|
1525
|
+
const slices = getValuedSlices();
|
|
1526
|
+
const maxSlices = toNumber(box.maxSlices) || 0;
|
|
1527
|
+
if (!maxSlices || slices.length <= maxSlices) return { kept: slices, folded: [] };
|
|
1528
|
+
|
|
1529
|
+
const biggest = slices.slice().sort(function (first, second) { return second.value - first.value; });
|
|
1530
|
+
const keptSlices = new Set(biggest.slice(0, Math.max(1, maxSlices - 1)));
|
|
1531
|
+
return {
|
|
1532
|
+
kept: slices.filter(function (slice) { return keptSlices.has(slice); }),
|
|
1533
|
+
folded: slices.filter(function (slice) { return !keptSlices.has(slice); }),
|
|
1534
|
+
};
|
|
1535
|
+
|
|
1536
|
+
};
|
|
1537
|
+
|
|
1538
|
+
// Who gets a color of the theme. WHY not only the slices with a value: A slice keeps its color, also while its value is 0.
|
|
1539
|
+
const getSliceColorKeys = function () {
|
|
1540
|
+
const dataset = box.data.datasets[0];
|
|
1541
|
+
const parts = splitSlices();
|
|
1542
|
+
const keys = [];
|
|
1543
|
+
if (!dataset) return keys;
|
|
1544
|
+
if (parts.folded.length) return parts.kept.map(function (slice) { return getSliceKey(slice.index); });
|
|
1545
|
+
for (let index = 0; index < getSliceCount(dataset); index++) keys.push(getSliceKey(index));
|
|
1546
|
+
return keys;
|
|
1547
|
+
};
|
|
1548
|
+
|
|
1549
|
+
const getSliceColor = function (dataset, index) {
|
|
1550
|
+
if (index === GraphBox.OTHER_SLICE) return colors.otherColor;
|
|
1551
|
+
const ownColor = dataset.colors && dataset.colors[index];
|
|
1552
|
+
return ownColor || colors.colors[sliceColorIndexes.get(getSliceKey(index))] || colors.otherColor;
|
|
1553
|
+
};
|
|
1554
|
+
|
|
1555
|
+
const isSliceHidden = function (index) {
|
|
1556
|
+
return hiddenSliceKeys.has(getSliceKey(index));
|
|
1557
|
+
};
|
|
1558
|
+
|
|
1559
|
+
// The slices on the screen: { index, value, color }, and "Other" with its small slices.
|
|
1560
|
+
const createSlices = function () {
|
|
1561
|
+
|
|
1562
|
+
const dataset = box.data.datasets[0];
|
|
1563
|
+
const parts = splitSlices();
|
|
1564
|
+
const slices = parts.kept.filter(function (slice) {
|
|
1565
|
+
return !isSliceHidden(slice.index);
|
|
1566
|
+
}).map(function (slice) {
|
|
1567
|
+
return { index: slice.index, value: slice.value, color: getSliceColor(dataset, slice.index) };
|
|
1568
|
+
});
|
|
1569
|
+
|
|
1570
|
+
if (parts.folded.length && !isSliceHidden(GraphBox.OTHER_SLICE)) {
|
|
1571
|
+
slices.push({
|
|
1572
|
+
index: GraphBox.OTHER_SLICE,
|
|
1573
|
+
value: getTotal(parts.folded),
|
|
1574
|
+
color: colors.otherColor,
|
|
1575
|
+
folded: parts.folded,
|
|
1576
|
+
});
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
return slices;
|
|
1580
|
+
|
|
1581
|
+
};
|
|
1582
|
+
|
|
1583
|
+
const addSliceAngles = function (slices, total) {
|
|
1584
|
+
let angle = TOP_ANGLE;
|
|
1585
|
+
slices.forEach(function (slice) {
|
|
1586
|
+
slice.startAngle = angle;
|
|
1587
|
+
angle += slice.value / total * FULL_CIRCLE;
|
|
1588
|
+
slice.endAngle = angle;
|
|
1589
|
+
});
|
|
1590
|
+
};
|
|
1591
|
+
|
|
1592
|
+
const getTotal = function (slices) {
|
|
1593
|
+
return slices.reduce(function (sum, slice) { return sum + slice.value; }, 0);
|
|
1594
|
+
};
|
|
1595
|
+
|
|
1596
|
+
const addSlice = function (layer, slice, shape, outerRadius) {
|
|
1597
|
+
return addShape(layer, "path", {
|
|
1598
|
+
d: GraphBox.slicePath(shape.center, shape.innerRadius, outerRadius, slice.startAngle, slice.endAngle, _s.pie.gap),
|
|
1599
|
+
fill: slice.color,
|
|
1600
|
+
});
|
|
1601
|
+
};
|
|
1602
|
+
|
|
1603
|
+
// The text in the hole: it gets smaller when it has no room.
|
|
1604
|
+
const drawPieCenter = function (shape) {
|
|
1605
|
+
|
|
1606
|
+
if (!shape.innerRadius || !box.centerText) return;
|
|
1607
|
+
|
|
1608
|
+
const roomWidth = shape.innerRadius * 1.6;
|
|
1609
|
+
const family = "opensans-bold";
|
|
1610
|
+
const fullWidth = GraphBox.measureText(box.centerText, _s.pie.centerFontSize, family);
|
|
1611
|
+
const fontSize = Math.min(_s.pie.centerFontSize, _s.pie.centerFontSize * roomWidth / fullWidth);
|
|
1612
|
+
const subHeight = (box.centerSubText) ? getAxisTextHeight() : 0;
|
|
1613
|
+
const center = shape.center;
|
|
1614
|
+
|
|
1615
|
+
const label = addText(markLayer, box.centerText, center.x, center.y - subHeight / 2, "middle", colors.titleColor);
|
|
1616
|
+
label.setAttribute("font-size", fontSize);
|
|
1617
|
+
label.setAttribute("font-family", family);
|
|
1618
|
+
|
|
1619
|
+
if (!subHeight) return;
|
|
1620
|
+
const subText = GraphBox.fitText(box.centerSubText, roomWidth, _s.axis.fontSize, _s.axis.fontFamily);
|
|
1621
|
+
addText(markLayer, subText, center.x, center.y + fontSize / 2 + subHeight / 2 - 2, "middle", colors.textColor);
|
|
1622
|
+
|
|
1623
|
+
};
|
|
1624
|
+
|
|
1625
|
+
// WHY: When the values already are percents (they add up to 100), a second percent says nothing.
|
|
1626
|
+
const getShareText = function (value, total) {
|
|
1627
|
+
if (Math.round(total) === 100) return "";
|
|
1628
|
+
return GraphBox.formatPercent(value / total, box.locale);
|
|
1629
|
+
};
|
|
1630
|
+
|
|
1631
|
+
// A slice shows its share (or its value, when the values are already percents), only when it fits.
|
|
1632
|
+
const drawSliceValue = function (slice, shape, total) {
|
|
1633
|
+
|
|
1634
|
+
const text = getShareText(slice.value, total) || formatValueText(slice.value);
|
|
1635
|
+
const isPie = (shape.innerRadius === 0);
|
|
1636
|
+
const PIE_LABEL_PLACE = 0.65;
|
|
1637
|
+
const radius = (isPie) ? shape.outerRadius * PIE_LABEL_PLACE : (shape.outerRadius + shape.innerRadius) / 2;
|
|
1638
|
+
const sweep = slice.endAngle - slice.startAngle;
|
|
1639
|
+
const halfAngle = Math.min(sweep / 2, Math.PI / 2);
|
|
1640
|
+
const chordRoom = 2 * radius * Math.sin(halfAngle) - _s.values.sidePadding * 2;
|
|
1641
|
+
const ringRoom = (isPie) ? chordRoom : shape.outerRadius - shape.innerRadius - _s.values.sidePadding * 2;
|
|
1642
|
+
const textWidth = measureAxisText(text);
|
|
1643
|
+
if (textWidth > chordRoom || textWidth > ringRoom || _s.axis.fontSize > chordRoom) return;
|
|
1644
|
+
|
|
1645
|
+
const angle = (slice.startAngle + slice.endAngle) / 2;
|
|
1646
|
+
const x = shape.center.x + radius * Math.cos(angle);
|
|
1647
|
+
const y = shape.center.y + radius * Math.sin(angle);
|
|
1648
|
+
const label = addText(valueLayer, text, x, y, "middle", GraphBox.getTextColorOn(slice.color));
|
|
1649
|
+
label.setAttribute("font-family", "opensans-bold");
|
|
1650
|
+
|
|
1651
|
+
};
|
|
1652
|
+
|
|
1653
|
+
// The tooltip of "Other" names its biggest small slices, and how many more there are.
|
|
1654
|
+
const getFoldedRows = function (slice) {
|
|
1655
|
+
|
|
1656
|
+
if (!slice.folded) return [];
|
|
1657
|
+
|
|
1658
|
+
const biggest = slice.folded.slice().sort(function (first, second) { return second.value - first.value; });
|
|
1659
|
+
const rows = biggest.slice(0, _s.pie.otherRows).map(function (foldedSlice) {
|
|
1660
|
+
return { color: "transparent", valueText: formatValueText(foldedSlice.value), nameText: getLabelText(foldedSlice.index) };
|
|
1661
|
+
});
|
|
1662
|
+
|
|
1663
|
+
const restCount = biggest.length - rows.length;
|
|
1664
|
+
if (restCount > 0) rows.push({ color: "transparent", valueText: "+" + restCount, nameText: "" });
|
|
1665
|
+
return rows;
|
|
1666
|
+
|
|
1667
|
+
};
|
|
1668
|
+
|
|
1669
|
+
const createPieView = function (slices, shape, total) {
|
|
1670
|
+
|
|
1671
|
+
const findSlice = function (item) {
|
|
1672
|
+
return slices.find(function (slice) { return slice.index === item.index; });
|
|
1673
|
+
};
|
|
1674
|
+
|
|
1675
|
+
return {
|
|
1676
|
+
findItem: function (x, y) {
|
|
1677
|
+
const distance = Math.hypot(x - shape.center.x, y - shape.center.y);
|
|
1678
|
+
if (distance > shape.outerRadius + _s.pie.hoverGrow || distance < shape.innerRadius) return null;
|
|
1679
|
+
let angle = Math.atan2(y - shape.center.y, x - shape.center.x);
|
|
1680
|
+
if (angle < TOP_ANGLE) angle += FULL_CIRCLE;
|
|
1681
|
+
const slice = slices.find(function (candidate) { return angle < candidate.endAngle; });
|
|
1682
|
+
return (slice) ? { index: slice.index, datasetIndex: 0 } : null;
|
|
1683
|
+
},
|
|
1684
|
+
stepItem: function (item, step) {
|
|
1685
|
+
const place = (item) ? slices.indexOf(findSlice(item)) + step : 0;
|
|
1686
|
+
const slice = slices[Math.min(slices.length - 1, Math.max(0, place))];
|
|
1687
|
+
return { index: slice.index, datasetIndex: 0 };
|
|
1688
|
+
},
|
|
1689
|
+
hasItem: function (item) {
|
|
1690
|
+
return !!findSlice(item);
|
|
1691
|
+
},
|
|
1692
|
+
paintItem: function (item) {
|
|
1693
|
+
// WHY a copy over it: The slice itself is not made again; the copy goes with the next move.
|
|
1694
|
+
addSlice(overlayLayer, findSlice(item), shape, shape.outerRadius + _s.pie.hoverGrow);
|
|
1695
|
+
},
|
|
1696
|
+
getReadout: function (item) {
|
|
1697
|
+
const slice = findSlice(item);
|
|
1698
|
+
const row = {
|
|
1699
|
+
color: slice.color,
|
|
1700
|
+
valueText: formatValueText(slice.value),
|
|
1701
|
+
nameText: getShareText(slice.value, total),
|
|
1702
|
+
};
|
|
1703
|
+
return { titleText: getSliceName(slice.index), rows: [row].concat(getFoldedRows(slice)) };
|
|
1704
|
+
},
|
|
1705
|
+
// For the keyboard: on the middle of the slice.
|
|
1706
|
+
getAnchor: function (item) {
|
|
1707
|
+
const slice = findSlice(item);
|
|
1708
|
+
const angle = (slice.startAngle + slice.endAngle) / 2;
|
|
1709
|
+
const radius = (shape.outerRadius + shape.innerRadius) / 2;
|
|
1710
|
+
return { x: shape.center.x + radius * Math.cos(angle), y: shape.center.y + radius * Math.sin(angle) };
|
|
1711
|
+
},
|
|
1712
|
+
};
|
|
1713
|
+
|
|
1714
|
+
};
|
|
1715
|
+
|
|
1716
|
+
const drawPie = function (width, height) {
|
|
1717
|
+
|
|
1718
|
+
const slices = createSlices();
|
|
1719
|
+
const total = getTotal(slices);
|
|
1720
|
+
if (!(total > 0)) return null;
|
|
1721
|
+
|
|
1722
|
+
const outerRadius = Math.max(1, Math.min(width, height) / 2 - _s.pie.hoverGrow);
|
|
1723
|
+
const shape = {
|
|
1724
|
+
center: { x: width / 2, y: height / 2 },
|
|
1725
|
+
outerRadius: outerRadius,
|
|
1726
|
+
innerRadius: (box.type === "doughnut") ? outerRadius * _s.pie.hole : 0,
|
|
1727
|
+
};
|
|
1728
|
+
|
|
1729
|
+
addSliceAngles(slices, total);
|
|
1730
|
+
slices.forEach(function (slice) {
|
|
1731
|
+
const sliceShape = addSlice(markLayer, slice, shape, outerRadius);
|
|
1732
|
+
rememberMark("slice", "", slice.index, sliceShape, { isSlice: 1 });
|
|
1733
|
+
if (basic.isOn(box.showValues)) drawSliceValue(slice, shape, total);
|
|
1734
|
+
});
|
|
1735
|
+
drawPieCenter(shape);
|
|
1736
|
+
|
|
1737
|
+
return createPieView(slices, shape, total);
|
|
1738
|
+
|
|
1739
|
+
};
|
|
1740
|
+
|
|
1741
|
+
// THE RADAR:
|
|
1742
|
+
|
|
1743
|
+
// The place of the chart: its center, its radius and the labels that fit at its sides.
|
|
1744
|
+
const measureRadar = function (indexCount, width, height) {
|
|
1745
|
+
const maxLabelWidth = width * _s.radar.maxLabelShare;
|
|
1746
|
+
const texts = getLabelTexts(indexCount).map(function (text) {
|
|
1747
|
+
return GraphBox.fitText(text, maxLabelWidth, _s.axis.fontSize, _s.axis.fontFamily);
|
|
1748
|
+
});
|
|
1749
|
+
const sideRoom = measureWidestText(texts) + _s.axis.labelGap;
|
|
1750
|
+
const upRoom = getAxisTextHeight() + _s.axis.labelGap;
|
|
1751
|
+
return {
|
|
1752
|
+
center: { x: width / 2, y: height / 2 },
|
|
1753
|
+
radius: Math.max(1, Math.min(width / 2 - sideRoom, height / 2 - upRoom)),
|
|
1754
|
+
texts: texts,
|
|
1755
|
+
indexCount: indexCount,
|
|
1756
|
+
};
|
|
1757
|
+
};
|
|
1758
|
+
|
|
1759
|
+
const getSpokeAngle = function (shape, index) {
|
|
1760
|
+
return TOP_ANGLE + index / shape.indexCount * FULL_CIRCLE;
|
|
1761
|
+
};
|
|
1762
|
+
|
|
1763
|
+
const toRadarPoint = function (shape, index, value) {
|
|
1764
|
+
const scale = shape.scale;
|
|
1765
|
+
const share = (value - scale.min) / ((scale.max - scale.min) || 1);
|
|
1766
|
+
const angle = getSpokeAngle(shape, index);
|
|
1767
|
+
return {
|
|
1768
|
+
x: shape.center.x + share * shape.radius * Math.cos(angle),
|
|
1769
|
+
y: shape.center.y + share * shape.radius * Math.sin(angle),
|
|
1770
|
+
};
|
|
1771
|
+
};
|
|
1772
|
+
|
|
1773
|
+
const drawRadarGrid = function (shape) {
|
|
1774
|
+
|
|
1775
|
+
const indexes = [];
|
|
1776
|
+
for (let index = 0; index < shape.indexCount; index++) indexes.push(index);
|
|
1777
|
+
|
|
1778
|
+
shape.scale.ticks.forEach(function (tick) {
|
|
1779
|
+
const points = indexes.map(function (index) { return toRadarPoint(shape, index, tick); });
|
|
1780
|
+
addShape(gridLayer, "path", {
|
|
1781
|
+
d: GraphBox.polygonPath(points),
|
|
1782
|
+
fill: "none",
|
|
1783
|
+
stroke: colors.gridColor,
|
|
1784
|
+
"stroke-width": 1,
|
|
1785
|
+
});
|
|
1786
|
+
});
|
|
1787
|
+
|
|
1788
|
+
indexes.forEach(function (index) {
|
|
1789
|
+
const end = toRadarPoint(shape, index, shape.scale.max);
|
|
1790
|
+
addLine(gridLayer, shape.center.x, shape.center.y, end.x, end.y, colors.gridColor);
|
|
1791
|
+
});
|
|
1792
|
+
|
|
1793
|
+
};
|
|
1794
|
+
|
|
1795
|
+
const drawRadarLabels = function (shape) {
|
|
1796
|
+
const distance = shape.radius + _s.axis.labelGap;
|
|
1797
|
+
shape.texts.forEach(function (text, index) {
|
|
1798
|
+
const angle = getSpokeAngle(shape, index);
|
|
1799
|
+
const cosine = Math.cos(angle);
|
|
1800
|
+
const SIDE_LIMIT = 0.2; // A label near the top or the bottom stays in the middle of its spoke.
|
|
1801
|
+
let anchor = "middle";
|
|
1802
|
+
if (cosine > SIDE_LIMIT) anchor = "start";
|
|
1803
|
+
if (cosine < -SIDE_LIMIT) anchor = "end";
|
|
1804
|
+
const x = shape.center.x + distance * cosine;
|
|
1805
|
+
const y = shape.center.y + distance * Math.sin(angle) + Math.sin(angle) * getAxisTextHeight() / 2;
|
|
1806
|
+
addText(gridLayer, text, x, y, anchor, colors.textColor);
|
|
1807
|
+
});
|
|
1808
|
+
};
|
|
1809
|
+
|
|
1810
|
+
// The numbers of the rings: on the first spoke, with a ring in the color of the box, so a line does not cut them.
|
|
1811
|
+
const drawRadarTicks = function (shape) {
|
|
1812
|
+
if (!basic.isOn(_s.radar.showTicks)) return;
|
|
1813
|
+
shape.scale.ticks.forEach(function (tick, tickIndex) {
|
|
1814
|
+
if (tick === shape.scale.min) return;
|
|
1815
|
+
const point = toRadarPoint(shape, 0, tick);
|
|
1816
|
+
addClearText(gridLayer, shape.scale.tickTexts[tickIndex], point.x + 4, point.y, "start", colors.mutedTextColor);
|
|
1817
|
+
});
|
|
1818
|
+
};
|
|
1819
|
+
|
|
1820
|
+
const drawRadarSeries = function (seriesItem, shape) {
|
|
1821
|
+
|
|
1822
|
+
seriesItem.points = [];
|
|
1823
|
+
seriesItem.ranges.forEach(function (range, index) {
|
|
1824
|
+
if (range) seriesItem.points[index] = toRadarPoint(shape, index, range.to);
|
|
1825
|
+
});
|
|
1826
|
+
|
|
1827
|
+
const seriesKey = getSeriesKeyOf(seriesItem);
|
|
1828
|
+
const polygon = addShape(markLayer, "path", {
|
|
1829
|
+
d: GraphBox.polygonPath(seriesItem.points.filter(Boolean)),
|
|
1830
|
+
fill: seriesItem.color,
|
|
1831
|
+
"fill-opacity": _s.radar.fillOpacity,
|
|
1832
|
+
stroke: seriesItem.color,
|
|
1833
|
+
"stroke-width": _s.line.width,
|
|
1834
|
+
"stroke-linejoin": "round",
|
|
1835
|
+
});
|
|
1836
|
+
rememberMark("line", seriesKey, 0, polygon);
|
|
1837
|
+
|
|
1838
|
+
if (shape.indexCount * _s.line.pointSpace > shape.radius * FULL_CIRCLE) return; // No room for the points
|
|
1839
|
+
seriesItem.points.forEach(function (point, index) {
|
|
1840
|
+
const dot = addPoint(markLayer, point, seriesItem.color, _s.line.pointRadius - 1);
|
|
1841
|
+
rememberMark("point", seriesKey, index, dot, { point: point, isOnLine: 1 });
|
|
1842
|
+
});
|
|
1843
|
+
|
|
1844
|
+
};
|
|
1845
|
+
|
|
1846
|
+
const createRadarView = function (series, shape) {
|
|
1847
|
+
|
|
1848
|
+
const count = shape.indexCount;
|
|
1849
|
+
|
|
1850
|
+
return {
|
|
1851
|
+
findItem: function (x, y) {
|
|
1852
|
+
const distanceX = x - shape.center.x;
|
|
1853
|
+
const distanceY = y - shape.center.y;
|
|
1854
|
+
if (Math.hypot(distanceX, distanceY) > shape.radius + _s.axis.labelGap) return null;
|
|
1855
|
+
const angle = Math.atan2(distanceY, distanceX) - TOP_ANGLE;
|
|
1856
|
+
const index = (Math.round(angle / FULL_CIRCLE * count) + count) % count;
|
|
1857
|
+
return { index: index, datasetIndex: findNearestDataset(series, index, x, y) };
|
|
1858
|
+
},
|
|
1859
|
+
stepItem: function (item, step) {
|
|
1860
|
+
if (!item) return { index: 0, datasetIndex: null };
|
|
1861
|
+
return { index: (item.index + step + count) % count, datasetIndex: null };
|
|
1862
|
+
},
|
|
1863
|
+
hasItem: function (item) {
|
|
1864
|
+
return (item.index < count);
|
|
1865
|
+
},
|
|
1866
|
+
paintItem: function (item) {
|
|
1867
|
+
const end = toRadarPoint(shape, item.index, shape.scale.max);
|
|
1868
|
+
addLine(washLayer, shape.center.x, shape.center.y, end.x, end.y, colors.axisColor);
|
|
1869
|
+
paintActivePoints(series, item.index);
|
|
1870
|
+
},
|
|
1871
|
+
getReadout: function (item) {
|
|
1872
|
+
return getPlaceReadout(series, item.index);
|
|
1873
|
+
},
|
|
1874
|
+
getAnchor: function (item) {
|
|
1875
|
+
return toRadarPoint(shape, item.index, shape.scale.max);
|
|
1876
|
+
},
|
|
1877
|
+
};
|
|
1878
|
+
|
|
1879
|
+
};
|
|
1880
|
+
|
|
1881
|
+
const drawRadar = function (width, height) {
|
|
1882
|
+
|
|
1883
|
+
const series = getVisibleSeries();
|
|
1884
|
+
const indexCount = getIndexCount(series);
|
|
1885
|
+
addValueRanges(series, indexCount);
|
|
1886
|
+
|
|
1887
|
+
const limits = getValueLimits(series);
|
|
1888
|
+
if (!limits) return null;
|
|
1889
|
+
|
|
1890
|
+
const shape = measureRadar(indexCount, width, height);
|
|
1891
|
+
shape.scale = createValueScale(limits, shape.radius, _s.radar.ringSpace);
|
|
1892
|
+
|
|
1893
|
+
drawRadarGrid(shape);
|
|
1894
|
+
drawRadarLabels(shape);
|
|
1895
|
+
drawRadarTicks(shape);
|
|
1896
|
+
series.forEach(function (seriesItem) {
|
|
1897
|
+
drawRadarSeries(seriesItem, shape);
|
|
1898
|
+
});
|
|
1899
|
+
|
|
1900
|
+
return createRadarView(series, shape);
|
|
1901
|
+
|
|
1902
|
+
};
|
|
1903
|
+
|
|
1904
|
+
// THE SCATTER AND THE BUBBLE:
|
|
1905
|
+
|
|
1906
|
+
const isScatterType = function () {
|
|
1907
|
+
return (box.type === "scatter" || box.type === "bubble");
|
|
1908
|
+
};
|
|
1909
|
+
|
|
1910
|
+
// A value of a dataset: { x, y }, [x, y], { x, y, r }, [x, y, r]. null: it can not be drawn.
|
|
1911
|
+
const toScatterValue = function (item) {
|
|
1912
|
+
if (item === null || item === undefined) return null;
|
|
1913
|
+
const source = (Array.isArray(item)) ? { x: item[0], y: item[1], r: item[2] } : item;
|
|
1914
|
+
const x = toNumber(source.x);
|
|
1915
|
+
const y = toNumber(source.y);
|
|
1916
|
+
if (x === null || y === null) return null;
|
|
1917
|
+
return { x: x, y: y, size: toNumber(source.r), label: source.label };
|
|
1918
|
+
};
|
|
1919
|
+
|
|
1920
|
+
const createScatterPoints = function (series) {
|
|
1921
|
+
const points = [];
|
|
1922
|
+
series.forEach(function (seriesItem) {
|
|
1923
|
+
seriesItem.dataset.data.forEach(function (item, index) {
|
|
1924
|
+
const value = toScatterValue(item);
|
|
1925
|
+
if (!value) return;
|
|
1926
|
+
points.push(Object.assign(value, {
|
|
1927
|
+
index: index,
|
|
1928
|
+
datasetIndex: seriesItem.datasetIndex,
|
|
1929
|
+
color: getMarkColor(seriesItem, index),
|
|
1930
|
+
seriesName: seriesItem.dataset.label || "",
|
|
1931
|
+
}));
|
|
1932
|
+
});
|
|
1933
|
+
});
|
|
1934
|
+
return points;
|
|
1935
|
+
};
|
|
1936
|
+
|
|
1937
|
+
const getLimitsOf = function (numbers, fixedLow, fixedHigh) {
|
|
1938
|
+
return applyFixedLimits(Math.min.apply(null, numbers), Math.max.apply(null, numbers), fixedLow, fixedHigh);
|
|
1939
|
+
};
|
|
1940
|
+
|
|
1941
|
+
const formatXText = function (value) {
|
|
1942
|
+
if (box.formatX) return String(box.formatX(value));
|
|
1943
|
+
return GraphBox.formatNumber(value, box.locale);
|
|
1944
|
+
};
|
|
1945
|
+
|
|
1946
|
+
const formatXTickText = function (value, decimals) {
|
|
1947
|
+
if (box.formatX) return String(box.formatX(value));
|
|
1948
|
+
return GraphBox.formatCompactNumber(value, box.locale, decimals);
|
|
1949
|
+
};
|
|
1950
|
+
|
|
1951
|
+
// The radius of every point. (The area of a bubble follows its value, not its width: the eye reads the area.)
|
|
1952
|
+
const addPointRadiuses = function (points) {
|
|
1953
|
+
if (box.type !== "bubble") {
|
|
1954
|
+
points.forEach(function (point) { point.radius = _s.line.pointRadius; });
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
const biggest = points.reduce(function (size, point) { return Math.max(size, point.size || 0); }, 0);
|
|
1958
|
+
points.forEach(function (point) {
|
|
1959
|
+
const share = (biggest > 0) ? Math.sqrt(Math.max(0, point.size || 0) / biggest) : 1;
|
|
1960
|
+
point.radius = Math.max(_s.line.pointRing, share * _s.scatter.maxBubble);
|
|
1961
|
+
});
|
|
1962
|
+
};
|
|
1963
|
+
|
|
1964
|
+
const measureScatterPlot = function (points, width, height) {
|
|
1965
|
+
|
|
1966
|
+
const yValues = points.map(function (point) { return point.y; }).concat(getHeldValues());
|
|
1967
|
+
const yLimits = getLimitsOf(yValues, box.minValue, box.maxValue);
|
|
1968
|
+
yLimits.fixedStep = toNumber(box.valueStep);
|
|
1969
|
+
const xLimits = getLimitsOf(points.map(function (point) { return point.x; }), box.minX, box.maxX);
|
|
1970
|
+
const titleRooms = getAxisTitleRooms();
|
|
1971
|
+
const textHeight = getAxisTextHeight();
|
|
1972
|
+
const labelGap = _s.axis.labelGap;
|
|
1973
|
+
const edgeRoom = getPointRoom();
|
|
1974
|
+
|
|
1975
|
+
const top = edgeRoom;
|
|
1976
|
+
const bottom = Math.max(top + 1, height - (textHeight + labelGap + titleRooms.bottom));
|
|
1977
|
+
const yScale = createValueScale(yLimits, bottom - top);
|
|
1978
|
+
const left = titleRooms.left + Math.ceil(measureWidestText(yScale.tickTexts)) + labelGap;
|
|
1979
|
+
|
|
1980
|
+
const xTickWidth = measureWidestText([formatXTickText(xLimits.low, 0), formatXTickText(xLimits.high, 0)]);
|
|
1981
|
+
const right = Math.max(left + 1, width - Math.max(edgeRoom, Math.ceil(xTickWidth / 2)));
|
|
1982
|
+
const xTickSpace = Math.max(_s.axis.sideTickSpace, xTickWidth + _s.axis.labelSpace);
|
|
1983
|
+
const xScale = createValueScale(xLimits, right - left, xTickSpace, formatXTickText);
|
|
1984
|
+
const lastRight = Math.min(right, getRightOfLastTick(xScale, width));
|
|
1985
|
+
|
|
1986
|
+
return { left: left, top: top, right: Math.max(left + 1, lastRight), bottom: bottom, xScale: xScale, yScale: yScale };
|
|
1987
|
+
|
|
1988
|
+
};
|
|
1989
|
+
|
|
1990
|
+
const createScatterAxes = function (plot) {
|
|
1991
|
+
|
|
1992
|
+
// WHY the inset: A bubble is big, so the smallest and the biggest values must not be drawn on the edges.
|
|
1993
|
+
const inset = (box.type === "bubble") ? _s.scatter.maxBubble : 0;
|
|
1994
|
+
const xScale = plot.xScale;
|
|
1995
|
+
const yScale = plot.yScale;
|
|
1996
|
+
const xLength = plot.right - plot.left - inset * 2;
|
|
1997
|
+
const yLength = plot.bottom - plot.top - inset * 2;
|
|
1998
|
+
|
|
1999
|
+
return {
|
|
2000
|
+
plot: plot,
|
|
2001
|
+
toX: function (value) {
|
|
2002
|
+
return plot.left + inset + (value - xScale.min) / ((xScale.max - xScale.min) || 1) * xLength;
|
|
2003
|
+
},
|
|
2004
|
+
toY: function (value) {
|
|
2005
|
+
return plot.bottom - inset - (value - yScale.min) / ((yScale.max - yScale.min) || 1) * yLength;
|
|
2006
|
+
},
|
|
2007
|
+
};
|
|
2008
|
+
|
|
2009
|
+
};
|
|
2010
|
+
|
|
2011
|
+
const drawScatterGrid = function (axes) {
|
|
2012
|
+
|
|
2013
|
+
const plot = axes.plot;
|
|
2014
|
+
const textHeight = getAxisTextHeight();
|
|
2015
|
+
|
|
2016
|
+
plot.yScale.ticks.forEach(function (tick, tickIndex) {
|
|
2017
|
+
const y = toPixelCenter(axes.toY(tick));
|
|
2018
|
+
addLine(gridLayer, plot.left, y, plot.right, y, colors.gridColor);
|
|
2019
|
+
addText(gridLayer, plot.yScale.tickTexts[tickIndex], plot.left - _s.axis.labelGap, y, "end");
|
|
2020
|
+
});
|
|
2021
|
+
|
|
2022
|
+
plot.xScale.ticks.forEach(function (tick, tickIndex) {
|
|
2023
|
+
const x = toPixelCenter(axes.toX(tick));
|
|
2024
|
+
addLine(gridLayer, x, plot.top, x, plot.bottom, colors.gridColor);
|
|
2025
|
+
addText(gridLayer, plot.xScale.tickTexts[tickIndex], x, plot.bottom + _s.axis.labelGap + textHeight / 2);
|
|
2026
|
+
});
|
|
2027
|
+
|
|
2028
|
+
const baseY = toPixelCenter((plot.yScale.min < 0 && plot.yScale.max > 0) ? axes.toY(0) : plot.bottom);
|
|
2029
|
+
const baseX = toPixelCenter((plot.xScale.min < 0 && plot.xScale.max > 0) ? axes.toX(0) : plot.left);
|
|
2030
|
+
addLine(gridLayer, plot.left, baseY, plot.right, baseY, colors.axisColor);
|
|
2031
|
+
addLine(gridLayer, baseX, plot.top, baseX, plot.bottom, colors.axisColor);
|
|
2032
|
+
|
|
2033
|
+
};
|
|
2034
|
+
|
|
2035
|
+
const drawScatterPoint = function (point) {
|
|
2036
|
+
const place = { x: point.px, y: point.py };
|
|
2037
|
+
const dot = addPoint(markLayer, place, point.color, point.radius);
|
|
2038
|
+
if (box.type === "bubble") dot.setAttribute("fill-opacity", _s.scatter.bubbleOpacity);
|
|
2039
|
+
rememberMark("point", point.datasetIndex, point.index, dot, { point: place });
|
|
2040
|
+
};
|
|
2041
|
+
|
|
2042
|
+
const findNearestPoint = function (points, x, y) {
|
|
2043
|
+
let nearest = null;
|
|
2044
|
+
let nearestDistance = Infinity;
|
|
2045
|
+
points.forEach(function (point) {
|
|
2046
|
+
const distance = Math.hypot(point.px - x, point.py - y);
|
|
2047
|
+
const reach = Math.max(_s.scatter.hitRadius, point.radius);
|
|
2048
|
+
if (distance > reach || distance >= nearestDistance) return;
|
|
2049
|
+
nearest = point;
|
|
2050
|
+
nearestDistance = distance;
|
|
2051
|
+
});
|
|
2052
|
+
return nearest;
|
|
2053
|
+
};
|
|
2054
|
+
|
|
2055
|
+
const getScatterReadout = function (point) {
|
|
2056
|
+
const rows = [
|
|
2057
|
+
{ color: point.color, valueText: formatValueText(point.y), nameText: box.yAxisText || "y" },
|
|
2058
|
+
{ color: "transparent", valueText: formatXText(point.x), nameText: box.xAxisText || "x" },
|
|
2059
|
+
];
|
|
2060
|
+
if (box.type === "bubble" && point.size !== null) {
|
|
2061
|
+
rows.push({ color: "transparent", valueText: GraphBox.formatNumber(point.size, box.locale), nameText: box.sizeText });
|
|
2062
|
+
}
|
|
2063
|
+
return { titleText: (point.label === undefined) ? point.seriesName : String(point.label), rows: rows };
|
|
2064
|
+
};
|
|
2065
|
+
|
|
2066
|
+
const createScatterView = function (points) {
|
|
2067
|
+
|
|
2068
|
+
const findPoint = function (item) {
|
|
2069
|
+
return points.find(function (point) {
|
|
2070
|
+
return (point.datasetIndex === item.datasetIndex && point.index === item.index);
|
|
2071
|
+
});
|
|
2072
|
+
};
|
|
2073
|
+
|
|
2074
|
+
return {
|
|
2075
|
+
findItem: function (x, y) {
|
|
2076
|
+
const point = findNearestPoint(points, x, y);
|
|
2077
|
+
return (point) ? { index: point.index, datasetIndex: point.datasetIndex } : null;
|
|
2078
|
+
},
|
|
2079
|
+
stepItem: function (item, step) {
|
|
2080
|
+
const place = (item) ? points.indexOf(findPoint(item)) + step : 0;
|
|
2081
|
+
const point = points[Math.min(points.length - 1, Math.max(0, place))];
|
|
2082
|
+
return { index: point.index, datasetIndex: point.datasetIndex };
|
|
2083
|
+
},
|
|
2084
|
+
hasItem: function (item) {
|
|
2085
|
+
return !!findPoint(item);
|
|
2086
|
+
},
|
|
2087
|
+
paintItem: function (item) {
|
|
2088
|
+
const point = findPoint(item);
|
|
2089
|
+
addPoint(overlayLayer, { x: point.px, y: point.py }, point.color, point.radius + 1);
|
|
2090
|
+
},
|
|
2091
|
+
getReadout: function (item) {
|
|
2092
|
+
return getScatterReadout(findPoint(item));
|
|
2093
|
+
},
|
|
2094
|
+
getAnchor: function (item) {
|
|
2095
|
+
const point = findPoint(item);
|
|
2096
|
+
return { x: point.px, y: point.py };
|
|
2097
|
+
},
|
|
2098
|
+
};
|
|
2099
|
+
|
|
2100
|
+
};
|
|
2101
|
+
|
|
2102
|
+
const drawScatter = function (width, height) {
|
|
2103
|
+
|
|
2104
|
+
const points = createScatterPoints(getVisibleSeries());
|
|
2105
|
+
if (!points.length) return null;
|
|
2106
|
+
|
|
2107
|
+
const axes = createScatterAxes(measureScatterPlot(points, width, height));
|
|
2108
|
+
|
|
2109
|
+
clipMarks(axes.plot);
|
|
2110
|
+
drawScatterGrid(axes);
|
|
2111
|
+
drawAxisTitles(axes.plot, height);
|
|
2112
|
+
addPointRadiuses(points);
|
|
2113
|
+
|
|
2114
|
+
points.forEach(function (point) {
|
|
2115
|
+
point.px = axes.toX(point.x);
|
|
2116
|
+
point.py = axes.toY(point.y);
|
|
2117
|
+
drawScatterPoint(point);
|
|
2118
|
+
});
|
|
2119
|
+
drawTargetLines(axes.plot, axes.plot.yScale, axes.toY, 0);
|
|
2120
|
+
|
|
2121
|
+
return createScatterView(points);
|
|
2122
|
+
|
|
2123
|
+
};
|
|
2124
|
+
|
|
2125
|
+
// THE PLOT:
|
|
2126
|
+
|
|
2127
|
+
const drawChart = function (width, height) {
|
|
2128
|
+
if (isPieType()) return drawPie(width, height);
|
|
2129
|
+
if (isScatterType()) return drawScatter(width, height);
|
|
2130
|
+
if (box.type === "radar") return drawRadar(width, height);
|
|
2131
|
+
return drawCartesian(width, height);
|
|
2132
|
+
};
|
|
2133
|
+
|
|
2134
|
+
const drawPlot = function () {
|
|
2135
|
+
|
|
2136
|
+
const width = box.plot.elem.clientWidth;
|
|
2137
|
+
const height = box.plot.elem.clientHeight;
|
|
2138
|
+
if (width <= 0 || height <= 0) {
|
|
2139
|
+
addedValueShift = null;
|
|
2140
|
+
return; // WHY: Not on the screen yet. onResize draws it when it comes.
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
drawnSize = width + "x" + height;
|
|
2144
|
+
clearLayers();
|
|
2145
|
+
|
|
2146
|
+
const oldMarks = marks;
|
|
2147
|
+
const oldAxes = drawnAxes;
|
|
2148
|
+
marks = new Map();
|
|
2149
|
+
drawnAxes = null;
|
|
2150
|
+
|
|
2151
|
+
svg.setAttribute("width", width);
|
|
2152
|
+
svg.setAttribute("height", height);
|
|
2153
|
+
svg.setAttribute("font-family", _s.axis.fontFamily);
|
|
2154
|
+
svg.setAttribute("font-size", _s.axis.fontSize);
|
|
2155
|
+
|
|
2156
|
+
view = drawChart(width, height);
|
|
2157
|
+
|
|
2158
|
+
box.lblEmpty.plainText = box.emptyText;
|
|
2159
|
+
box.lblEmpty.visible = (view) ? 0 : 1;
|
|
2160
|
+
applySummary();
|
|
2161
|
+
|
|
2162
|
+
if (activeItem && (!view || !view.hasItem(activeItem))) activeItem = null;
|
|
2163
|
+
paintActiveItem();
|
|
2164
|
+
|
|
2165
|
+
if (isChangeWaiting && isMotionOn()) playMotion(oldMarks, oldAxes);
|
|
2166
|
+
isChangeWaiting = 0;
|
|
2167
|
+
addedValueShift = null;
|
|
2168
|
+
|
|
2169
|
+
};
|
|
2170
|
+
|
|
2171
|
+
// The drawing of a change of the data: it may move. (A new size or a font does not.)
|
|
2172
|
+
const drawChange = function () {
|
|
2173
|
+
isChangeWaiting = 1;
|
|
2174
|
+
drawPlot();
|
|
2175
|
+
};
|
|
2176
|
+
|
|
2177
|
+
// THE MOTION OF A CHANGE:
|
|
2178
|
+
// WHY like this: Every drawing makes its shapes again. So a new shape is first put where the old one was, without a
|
|
2179
|
+
// transition, and then its transition takes it to its real place. Only transform and opacity change, and the
|
|
2180
|
+
// "d" of a line: a line has no other way to change its form, and it does not move the layout of the page.
|
|
2181
|
+
// (Safari can not move a "d": there a line and its points come with a fade, together.)
|
|
2182
|
+
|
|
2183
|
+
const isMotionOn = function () {
|
|
2184
|
+
if (box.animated != 1) return false;
|
|
2185
|
+
return !(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);
|
|
2186
|
+
};
|
|
2187
|
+
|
|
2188
|
+
const toMotionText = function (property, time = MOTION_TIME) {
|
|
2189
|
+
return property + " " + time + "s " + MOTION_EASE;
|
|
2190
|
+
};
|
|
2191
|
+
|
|
2192
|
+
const toPathText = function (path) {
|
|
2193
|
+
return 'path("' + path + '")';
|
|
2194
|
+
};
|
|
2195
|
+
|
|
2196
|
+
// The transform that puts a bar of the new drawing on the place of the old one.
|
|
2197
|
+
const getRectMatrix = function (rect, oldRect) {
|
|
2198
|
+
const scaleX = (rect.width) ? oldRect.width / rect.width : 1;
|
|
2199
|
+
const scaleY = (rect.height) ? oldRect.height / rect.height : 1;
|
|
2200
|
+
const moveX = oldRect.left - scaleX * rect.left;
|
|
2201
|
+
const moveY = oldRect.top - scaleY * rect.top;
|
|
2202
|
+
return "matrix(" + [scaleX, 0, 0, scaleY, moveX, moveY].join(",") + ")";
|
|
2203
|
+
};
|
|
2204
|
+
|
|
2205
|
+
// What a mark does: { shape, property, from, to }. null: it just stays.
|
|
2206
|
+
const createFade = function (shape, fromOpacity) {
|
|
2207
|
+
return { shape: shape, property: "opacity", from: String(fromOpacity), to: "1" };
|
|
2208
|
+
};
|
|
2209
|
+
|
|
2210
|
+
const createMove = function (mark, oldMark) {
|
|
2211
|
+
|
|
2212
|
+
const shape = mark.shape;
|
|
2213
|
+
if (!oldMark) return createFade(shape, 0);
|
|
2214
|
+
|
|
2215
|
+
// WHY a fade: The ends of an arc go on straight lines between their two places, so a moving slice loses its form.
|
|
2216
|
+
if (mark.isSlice) return createFade(shape, _s.pie.changeOpacity);
|
|
2217
|
+
|
|
2218
|
+
if (mark.rect) return { shape: shape, property: "transform", from: getRectMatrix(mark.rect, oldMark.rect), to: "none" };
|
|
2219
|
+
|
|
2220
|
+
// WHY together: A point that slides away from a line that is already at its new place looks broken.
|
|
2221
|
+
const isLineMark = (mark.isOnLine || !mark.point);
|
|
2222
|
+
if (isLineMark && !GraphBox.canMovePaths()) return createFade(shape, _s.line.changeOpacity);
|
|
2223
|
+
|
|
2224
|
+
if (mark.point) {
|
|
2225
|
+
const moveX = oldMark.point.x - mark.point.x;
|
|
2226
|
+
const moveY = oldMark.point.y - mark.point.y;
|
|
2227
|
+
return { shape: shape, property: "transform", from: "translate(" + moveX + "px, " + moveY + "px)", to: "none" };
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
const from = toPathText(oldMark.shape.getAttribute("d"));
|
|
2231
|
+
return { shape: shape, property: "d", from: from, to: toPathText(shape.getAttribute("d")) };
|
|
2232
|
+
|
|
2233
|
+
};
|
|
2234
|
+
|
|
2235
|
+
const runMoves = function (moves) {
|
|
2236
|
+
moves.forEach(function (move) {
|
|
2237
|
+
move.shape.style.transition = "none";
|
|
2238
|
+
move.shape.style[move.property] = move.from;
|
|
2239
|
+
});
|
|
2240
|
+
void svg.getBoundingClientRect(); // WHY: The start must be applied before the transitions are on.
|
|
2241
|
+
moves.forEach(function (move) {
|
|
2242
|
+
move.shape.style.transition = toMotionText(move.property);
|
|
2243
|
+
move.shape.style[move.property] = move.to;
|
|
2244
|
+
});
|
|
2245
|
+
};
|
|
2246
|
+
|
|
2247
|
+
// addValue(): the values stay as they are. Only their places change: one to the left (or closer, while the chart
|
|
2248
|
+
// fills up), and the scale. So one transform of all the marks puts the new drawing on the old one.
|
|
2249
|
+
const getAddedValueMatrix = function (oldAxes, newAxes, shift) {
|
|
2250
|
+
|
|
2251
|
+
const newStart = newAxes.toIndexPosition(0);
|
|
2252
|
+
const newEnd = newAxes.toIndexPosition(1);
|
|
2253
|
+
const oldStart = oldAxes.toIndexPosition(shift);
|
|
2254
|
+
const oldEnd = oldAxes.toIndexPosition(shift + 1);
|
|
2255
|
+
const scaleX = (oldEnd - oldStart) / ((newEnd - newStart) || 1);
|
|
2256
|
+
|
|
2257
|
+
const scale = newAxes.scale;
|
|
2258
|
+
const newBottom = newAxes.toValuePosition(scale.min);
|
|
2259
|
+
const newTop = newAxes.toValuePosition(scale.max);
|
|
2260
|
+
const oldBottom = oldAxes.toValuePosition(scale.min);
|
|
2261
|
+
const oldTop = oldAxes.toValuePosition(scale.max);
|
|
2262
|
+
const scaleY = (oldTop - oldBottom) / ((newTop - newBottom) || 1);
|
|
2263
|
+
|
|
2264
|
+
if (!scaleX || !scaleY) return null; // WHY: The first values: there is no width of a place to start from.
|
|
2265
|
+
return "matrix(" + [scaleX, 0, 0, scaleY, oldStart - scaleX * newStart, oldBottom - scaleY * newBottom].join(",") + ")";
|
|
2266
|
+
|
|
2267
|
+
};
|
|
2268
|
+
|
|
2269
|
+
const playAddedValueMotion = function (oldAxes) {
|
|
2270
|
+
const matrix = getAddedValueMatrix(oldAxes, drawnAxes, addedValueShift);
|
|
2271
|
+
if (matrix) runMoves([{ shape: markLayer, property: "transform", from: matrix, to: "none" }]);
|
|
2272
|
+
};
|
|
2273
|
+
|
|
2274
|
+
const playMotion = function (oldMarks, oldAxes) {
|
|
2275
|
+
|
|
2276
|
+
if (!oldMarks.size) return; // WHY: No motion at the first view.
|
|
2277
|
+
|
|
2278
|
+
const isAddedValue = (addedValueShift !== null && oldAxes && drawnAxes && !drawnAxes.isHorizontal);
|
|
2279
|
+
if (isAddedValue) {
|
|
2280
|
+
playAddedValueMotion(oldAxes);
|
|
2281
|
+
return;
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
const moves = [];
|
|
2285
|
+
marks.forEach(function (mark, name) {
|
|
2286
|
+
const move = createMove(mark, oldMarks.get(name));
|
|
2287
|
+
if (move) moves.push(move);
|
|
2288
|
+
});
|
|
2289
|
+
if (valueLayer.childElementCount) moves.push({ shape: valueLayer, property: "opacity", from: "0", to: "1" });
|
|
2290
|
+
runMoves(moves);
|
|
2291
|
+
|
|
2292
|
+
};
|
|
2293
|
+
|
|
2294
|
+
const applySummary = function () {
|
|
2295
|
+
box.plot.aria = { label: getSummaryText() };
|
|
2296
|
+
};
|
|
2297
|
+
|
|
2298
|
+
// WHY: A screen reader can not read an SVG drawing: the title and every value are read from this text.
|
|
2299
|
+
const getSummaryText = function () {
|
|
2300
|
+
const parts = [box.titleText || box.type + " chart"];
|
|
2301
|
+
if (box.subtitleText) parts.push(box.subtitleText);
|
|
2302
|
+
getVisibleSeries().forEach(function (seriesItem) {
|
|
2303
|
+
// WHY the limit: Nobody listens to thousands of values, and a live chart makes this text every second.
|
|
2304
|
+
const values = seriesItem.dataset.data.slice(0, SUMMARY_VALUE_COUNT).map(function (value, index) {
|
|
2305
|
+
if (isScatterType()) {
|
|
2306
|
+
const point = toScatterValue(value);
|
|
2307
|
+
return (point) ? formatXText(point.x) + " " + formatValueText(point.y) : "";
|
|
2308
|
+
}
|
|
2309
|
+
const number = toNumber(value);
|
|
2310
|
+
if (number === null) return "";
|
|
2311
|
+
return getLabelText(index) + " " + formatValueText(number);
|
|
2312
|
+
});
|
|
2313
|
+
parts.push((seriesItem.dataset.label || "") + " " + values.filter(Boolean).join(", "));
|
|
2314
|
+
});
|
|
2315
|
+
getTargetLines().forEach(function (line) {
|
|
2316
|
+
parts.push((line.label || "") + " " + formatValueText(toNumber(line.value)));
|
|
2317
|
+
});
|
|
2318
|
+
return parts.join(". ");
|
|
2319
|
+
};
|
|
2320
|
+
|
|
2321
|
+
// THE TOOLTIP:
|
|
2322
|
+
|
|
2323
|
+
const createTooltipRow = function () {
|
|
2324
|
+
|
|
2325
|
+
const row = createIn(box.tooltip, function () {
|
|
2326
|
+
const group = HGroup({ hug: 1, gap: 6, align: "left center" });
|
|
2327
|
+
group.key = Box({ width: _s.tooltip.keyWidth, height: _s.tooltip.keyHeight, round: _s.tooltip.keyHeight / 2 });
|
|
2328
|
+
group.key.shrink = 0;
|
|
2329
|
+
group.lblValue = Label({ fontSize: _s.tooltip.fontSize, fontFamily: "opensans-bold", css: { whiteSpace: "nowrap" } });
|
|
2330
|
+
group.lblName = Label({ fontSize: _s.tooltip.fontSize, ellipsis: 1 });
|
|
2331
|
+
endGroup();
|
|
2332
|
+
return group;
|
|
2333
|
+
});
|
|
2334
|
+
|
|
2335
|
+
tooltipRows.push(row);
|
|
2336
|
+
|
|
2337
|
+
};
|
|
2338
|
+
|
|
2339
|
+
const paintTooltipRow = function (row, rowData) {
|
|
2340
|
+
row.visible = (rowData) ? 1 : 0;
|
|
2341
|
+
if (!rowData) return;
|
|
2342
|
+
row.key.color = rowData.color;
|
|
2343
|
+
row.lblValue.plainText = rowData.valueText;
|
|
2344
|
+
row.lblValue.textColor = colors.tooltipTextColor;
|
|
2345
|
+
row.lblName.plainText = rowData.nameText;
|
|
2346
|
+
row.lblName.textColor = colors.tooltipMutedColor;
|
|
2347
|
+
row.lblName.visible = (rowData.nameText) ? 1 : 0;
|
|
2348
|
+
row.lblName.css = { maxWidth: Math.min(_s.tooltip.maxNameWidth, box.elem.clientWidth / 2) + "px" };
|
|
2349
|
+
};
|
|
2350
|
+
|
|
2351
|
+
const fillTooltip = function (readout) {
|
|
2352
|
+
const titleRoom = box.elem.clientWidth - (_s.tooltip.edge + _s.tooltip.padding[0]) * 2;
|
|
2353
|
+
box.lblTooltipTitle.css = { maxWidth: titleRoom + "px" };
|
|
2354
|
+
box.lblTooltipTitle.plainText = readout.titleText;
|
|
2355
|
+
box.lblTooltipTitle.visible = (readout.titleText) ? 1 : 0;
|
|
2356
|
+
while (tooltipRows.length < readout.rows.length) createTooltipRow();
|
|
2357
|
+
tooltipRows.forEach(function (row, rowIndex) {
|
|
2358
|
+
paintTooltipRow(row, readout.rows[rowIndex]);
|
|
2359
|
+
});
|
|
2360
|
+
};
|
|
2361
|
+
|
|
2362
|
+
// How many screen px is one px of this object? (page.fit() or a parent with a scale)
|
|
2363
|
+
const getZoom = function (element, rect) {
|
|
2364
|
+
return (rect.width / element.offsetWidth) || 1;
|
|
2365
|
+
};
|
|
2366
|
+
|
|
2367
|
+
const placeTooltip = function () {
|
|
2368
|
+
|
|
2369
|
+
const anchor = pointer || view.getAnchor(activeItem);
|
|
2370
|
+
const boxRect = box.elem.getBoundingClientRect();
|
|
2371
|
+
const plotRect = box.plot.elem.getBoundingClientRect();
|
|
2372
|
+
const zoom = getZoom(box.elem, boxRect);
|
|
2373
|
+
const distance = _s.tooltip.distance;
|
|
2374
|
+
const edge = _s.tooltip.edge;
|
|
2375
|
+
const tooltipWidth = box.tooltip.elem.offsetWidth;
|
|
2376
|
+
const tooltipHeight = box.tooltip.elem.offsetHeight;
|
|
2377
|
+
const anchorX = (plotRect.left - boxRect.left) / zoom + anchor.x - box.elem.clientLeft;
|
|
2378
|
+
const anchorY = (plotRect.top - boxRect.top) / zoom + anchor.y - box.elem.clientTop;
|
|
2379
|
+
|
|
2380
|
+
// It stays at the right of the mouse, or goes to its left when there is no room.
|
|
2381
|
+
let left = anchorX + distance;
|
|
2382
|
+
if (left + tooltipWidth > box.elem.clientWidth - edge) left = anchorX - distance - tooltipWidth;
|
|
2383
|
+
|
|
2384
|
+
moveTooltip(
|
|
2385
|
+
Math.max(edge, left),
|
|
2386
|
+
Math.max(edge, Math.min(box.elem.clientHeight - tooltipHeight - edge, anchorY - tooltipHeight / 2))
|
|
2387
|
+
);
|
|
2388
|
+
|
|
2389
|
+
};
|
|
2390
|
+
|
|
2391
|
+
// WHY transform when it moves: left and top would move the layout at every move of the mouse.
|
|
2392
|
+
const moveTooltip = function (left, top) {
|
|
2393
|
+
if (!isMotionOn()) {
|
|
2394
|
+
box.tooltip.left = left;
|
|
2395
|
+
box.tooltip.top = top;
|
|
2396
|
+
return;
|
|
2397
|
+
}
|
|
2398
|
+
box.tooltip.left = 0;
|
|
2399
|
+
box.tooltip.top = 0;
|
|
2400
|
+
box.tooltip.css = { transform: "translate(" + left + "px, " + top + "px)" };
|
|
2401
|
+
};
|
|
2402
|
+
|
|
2403
|
+
const showTooltip = function () {
|
|
2404
|
+
|
|
2405
|
+
const wasHidden = !isTooltipShown;
|
|
2406
|
+
isTooltipShown = 1;
|
|
2407
|
+
if (cancelTooltipHide) cancelTooltipHide();
|
|
2408
|
+
cancelTooltipHide = null;
|
|
2409
|
+
box.tooltip.visible = 1;
|
|
2410
|
+
|
|
2411
|
+
if (!isMotionOn()) {
|
|
2412
|
+
placeTooltip();
|
|
2413
|
+
return;
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
// It comes where it must be and fades in: it does not fly from where it was the last time.
|
|
2417
|
+
if (wasHidden) {
|
|
2418
|
+
box.tooltip.setMotionNow("none");
|
|
2419
|
+
box.tooltip.opacity = 0;
|
|
2420
|
+
placeTooltip();
|
|
2421
|
+
void box.tooltip.elem.offsetWidth; // WHY: The start must be applied before the transition is on.
|
|
2422
|
+
}
|
|
2423
|
+
box.tooltip.setMotionNow(toMotionText("transform") + ", " + toMotionText("opacity"));
|
|
2424
|
+
box.tooltip.opacity = 1;
|
|
2425
|
+
placeTooltip();
|
|
2426
|
+
|
|
2427
|
+
};
|
|
2428
|
+
|
|
2429
|
+
const hideTooltip = function () {
|
|
2430
|
+
|
|
2431
|
+
if (!isTooltipShown) return;
|
|
2432
|
+
isTooltipShown = 0;
|
|
2433
|
+
|
|
2434
|
+
if (!isMotionOn()) {
|
|
2435
|
+
box.tooltip.visible = 0;
|
|
2436
|
+
return;
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
box.tooltip.setMotionNow(toMotionText("opacity", TOOLTIP_CLOSE_TIME));
|
|
2440
|
+
box.tooltip.opacity = 0;
|
|
2441
|
+
cancelTooltipHide = box.after(TOOLTIP_CLOSE_TIME * 1000, function () {
|
|
2442
|
+
cancelTooltipHide = null;
|
|
2443
|
+
box.tooltip.visible = 0;
|
|
2444
|
+
});
|
|
2445
|
+
|
|
2446
|
+
};
|
|
2447
|
+
|
|
2448
|
+
// THE ACTIVE ITEM:
|
|
2449
|
+
|
|
2450
|
+
const paintActiveItem = function () {
|
|
2451
|
+
|
|
2452
|
+
washLayer.replaceChildren();
|
|
2453
|
+
overlayLayer.replaceChildren();
|
|
2454
|
+
|
|
2455
|
+
if (view && activeItem) view.paintItem(activeItem);
|
|
2456
|
+
|
|
2457
|
+
const readout = (view && activeItem) ? view.getReadout(activeItem) : null;
|
|
2458
|
+
if (!readout || !readout.rows.length) {
|
|
2459
|
+
hideTooltip();
|
|
2460
|
+
return;
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
fillTooltip(readout);
|
|
2464
|
+
showTooltip();
|
|
2465
|
+
|
|
2466
|
+
};
|
|
2467
|
+
|
|
2468
|
+
const isSameItem = function (first, second) {
|
|
2469
|
+
if (!first || !second) return first === second;
|
|
2470
|
+
return (first.index === second.index && first.datasetIndex === second.datasetIndex);
|
|
2471
|
+
};
|
|
2472
|
+
|
|
2473
|
+
const setActiveItem = function (item) {
|
|
2474
|
+
const hasChanged = !isSameItem(activeItem, item);
|
|
2475
|
+
activeItem = item;
|
|
2476
|
+
if (hasChanged) {
|
|
2477
|
+
paintActiveItem();
|
|
2478
|
+
return;
|
|
2479
|
+
}
|
|
2480
|
+
if (item && isTooltipShown) placeTooltip();
|
|
2481
|
+
};
|
|
2482
|
+
|
|
2483
|
+
const clearActiveItem = function () {
|
|
2484
|
+
pointer = null;
|
|
2485
|
+
setActiveItem(null);
|
|
2486
|
+
};
|
|
2487
|
+
|
|
2488
|
+
const getPointerPosition = function (event) {
|
|
2489
|
+
const rect = box.plot.elem.getBoundingClientRect();
|
|
2490
|
+
const zoom = getZoom(box.plot.elem, rect);
|
|
2491
|
+
return { x: (event.clientX - rect.left) / zoom, y: (event.clientY - rect.top) / zoom };
|
|
2492
|
+
};
|
|
2493
|
+
|
|
2494
|
+
// The keyboard chooses a place, not a dataset: the first one on the screen with a value there.
|
|
2495
|
+
const getFirstDatasetIndexAt = function (index) {
|
|
2496
|
+
const seriesItem = getVisibleSeries().find(function (candidate) {
|
|
2497
|
+
return getValue(candidate.dataset, index) !== null;
|
|
2498
|
+
});
|
|
2499
|
+
return (seriesItem) ? seriesItem.datasetIndex : 0;
|
|
2500
|
+
};
|
|
2501
|
+
|
|
2502
|
+
// "Other" of a pie is not a place of the data: its value is the total and otherItems names its small slices.
|
|
2503
|
+
const createOtherClickItem = function (dataset) {
|
|
2504
|
+
const folded = splitSlices().folded;
|
|
2505
|
+
return {
|
|
2506
|
+
datasetIndex: 0,
|
|
2507
|
+
index: GraphBox.OTHER_SLICE,
|
|
2508
|
+
label: box.otherText,
|
|
2509
|
+
value: getTotal(folded),
|
|
2510
|
+
datasetLabel: dataset.label || "",
|
|
2511
|
+
dataset: dataset,
|
|
2512
|
+
otherItems: folded.map(function (slice) {
|
|
2513
|
+
return { index: slice.index, label: box.data.labels[slice.index], value: slice.value };
|
|
2514
|
+
}),
|
|
2515
|
+
};
|
|
2516
|
+
};
|
|
2517
|
+
|
|
2518
|
+
// The item of a click: { datasetIndex, index, label, value, datasetLabel, dataset }
|
|
2519
|
+
const createClickItem = function (item) {
|
|
2520
|
+
const datasetIndex = (item.datasetIndex === null) ? getFirstDatasetIndexAt(item.index) : item.datasetIndex;
|
|
2521
|
+
const dataset = box.data.datasets[datasetIndex];
|
|
2522
|
+
if (!dataset) return null;
|
|
2523
|
+
if (item.index === GraphBox.OTHER_SLICE) return createOtherClickItem(dataset);
|
|
2524
|
+
return {
|
|
2525
|
+
datasetIndex: datasetIndex,
|
|
2526
|
+
index: item.index,
|
|
2527
|
+
label: box.data.labels[item.index],
|
|
2528
|
+
value: dataset.data[item.index],
|
|
2529
|
+
datasetLabel: dataset.label || "",
|
|
2530
|
+
dataset: dataset,
|
|
2531
|
+
};
|
|
2532
|
+
};
|
|
2533
|
+
|
|
2534
|
+
const runClickEvent = function (event) {
|
|
2535
|
+
const clickItem = (activeItem) ? createClickItem(activeItem) : null;
|
|
2536
|
+
if (clickItem) box.onClick(box, clickItem, event);
|
|
2537
|
+
};
|
|
2538
|
+
|
|
2539
|
+
const onPlotPointerMove = function (self, event) {
|
|
2540
|
+
if (!view) return;
|
|
2541
|
+
pointer = getPointerPosition(event);
|
|
2542
|
+
setActiveItem(view.findItem(pointer.x, pointer.y));
|
|
2543
|
+
if (hasClickEvent) box.plot.cursor = (activeItem) ? "pointer" : "default";
|
|
2544
|
+
};
|
|
2545
|
+
|
|
2546
|
+
// WHY not touch: A finger leaves the screen after every touch. The tooltip stays until a touch outside the chart.
|
|
2547
|
+
const onPlotPointerLeave = function (self, event) {
|
|
2548
|
+
if (event.pointerType !== "touch") clearActiveItem();
|
|
2549
|
+
};
|
|
2550
|
+
|
|
2551
|
+
const onDocumentPointerDown = function (self, event) {
|
|
2552
|
+
if (!activeItem || box.plot.elem.contains(event.target)) return;
|
|
2553
|
+
clearActiveItem();
|
|
2554
|
+
};
|
|
2555
|
+
|
|
2556
|
+
const onPlotKeyDown = function (self, event) {
|
|
2557
|
+
|
|
2558
|
+
if (!view) return;
|
|
2559
|
+
|
|
2560
|
+
if (event.key === "Escape") {
|
|
2561
|
+
clearActiveItem();
|
|
2562
|
+
return;
|
|
2563
|
+
}
|
|
2564
|
+
|
|
2565
|
+
if (event.key === "Enter") {
|
|
2566
|
+
runClickEvent(event);
|
|
2567
|
+
return;
|
|
2568
|
+
}
|
|
2569
|
+
|
|
2570
|
+
const step = STEP_KEYS[event.key];
|
|
2571
|
+
if (!step) return;
|
|
2572
|
+
event.preventDefault();
|
|
2573
|
+
pointer = null;
|
|
2574
|
+
setActiveItem(view.stepItem(activeItem, step));
|
|
2575
|
+
|
|
2576
|
+
};
|
|
2577
|
+
|
|
2578
|
+
// WHY focus-visible: The tooltip opens only for the keyboard. A click also gives the focus, and the mouse has its own.
|
|
2579
|
+
const onPlotFocus = function () {
|
|
2580
|
+
if (!view || activeItem || !box.plot.elem.matches(":focus-visible")) return;
|
|
2581
|
+
pointer = null;
|
|
2582
|
+
setActiveItem(view.stepItem(null, 0));
|
|
2583
|
+
};
|
|
2584
|
+
|
|
2585
|
+
// THE LEGEND:
|
|
2586
|
+
|
|
2587
|
+
// A key looks like its mark.
|
|
2588
|
+
const getKeyShape = function (dataset) {
|
|
2589
|
+
const type = getDatasetType(dataset);
|
|
2590
|
+
if (type === "bar") return "box";
|
|
2591
|
+
return (type === "scatter" || type === "bubble") ? "dot" : "line";
|
|
2592
|
+
};
|
|
2593
|
+
|
|
2594
|
+
const getSeriesEntries = function () {
|
|
2595
|
+
return box.data.datasets.map(function (dataset, position) {
|
|
2596
|
+
return {
|
|
2597
|
+
text: (dataset.showInLegend === 0 || dataset.showInLegend === false) ? "" : (dataset.label || ""),
|
|
2598
|
+
color: getSeriesColor(dataset, position),
|
|
2599
|
+
keyShape: getKeyShape(dataset),
|
|
2600
|
+
isHidden: basic.isOn(dataset.hidden),
|
|
2601
|
+
position: position,
|
|
2602
|
+
};
|
|
2603
|
+
});
|
|
2604
|
+
};
|
|
2605
|
+
|
|
2606
|
+
const createSliceEntry = function (dataset, index) {
|
|
2607
|
+
return {
|
|
2608
|
+
text: getSliceName(index),
|
|
2609
|
+
color: getSliceColor(dataset, index),
|
|
2610
|
+
keyShape: "box",
|
|
2611
|
+
isHidden: isSliceHidden(index),
|
|
2612
|
+
position: index,
|
|
2613
|
+
};
|
|
2614
|
+
};
|
|
2615
|
+
|
|
2616
|
+
// Every label; when small slices are one slice, only what is on the chart.
|
|
2617
|
+
const getSliceEntries = function () {
|
|
2618
|
+
|
|
2619
|
+
const dataset = box.data.datasets[0];
|
|
2620
|
+
if (!dataset) return [];
|
|
2621
|
+
|
|
2622
|
+
const parts = splitSlices();
|
|
2623
|
+
if (parts.folded.length) {
|
|
2624
|
+
const entries = parts.kept.map(function (slice) { return createSliceEntry(dataset, slice.index); });
|
|
2625
|
+
entries.push(createSliceEntry(dataset, GraphBox.OTHER_SLICE));
|
|
2626
|
+
return entries;
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
const entries = [];
|
|
2630
|
+
for (let index = 0; index < getSliceCount(dataset); index++) entries.push(createSliceEntry(dataset, index));
|
|
2631
|
+
return entries;
|
|
2632
|
+
|
|
2633
|
+
};
|
|
2634
|
+
|
|
2635
|
+
const getLegendEntries = function () {
|
|
2636
|
+
const entries = (isPieType()) ? getSliceEntries() : getSeriesEntries();
|
|
2637
|
+
return entries.filter(function (entry) { return entry.text !== ""; });
|
|
2638
|
+
};
|
|
2639
|
+
|
|
2640
|
+
const getLegendPosition = function () {
|
|
2641
|
+
if (box.legend === 0 || box.legend === false || box.legend === "none") return "none";
|
|
2642
|
+
if (box.legend !== "auto") return box.legend;
|
|
2643
|
+
if (isPieType()) return (box.elem.clientWidth >= _s.legend.sideMinWidth) ? "right" : "bottom";
|
|
2644
|
+
return (box.data.datasets.length >= 2) ? "top" : "none";
|
|
2645
|
+
};
|
|
2646
|
+
|
|
2647
|
+
const applyLegendPosition = function () {
|
|
2648
|
+
|
|
2649
|
+
const position = getLegendPosition();
|
|
2650
|
+
legendPlace = position;
|
|
2651
|
+
box.legendGroup.visible = (position === "none") ? 0 : 1;
|
|
2652
|
+
if (position === "none") return;
|
|
2653
|
+
|
|
2654
|
+
// WHY the limits and the scroll: A legend of many items must leave room for the chart.
|
|
2655
|
+
const isSide = (position === "left" || position === "right");
|
|
2656
|
+
box.body.css = { flexDirection: LEGEND_FLOWS[position] };
|
|
2657
|
+
box.legendGroup.width = (isSide) ? "auto" : "100%";
|
|
2658
|
+
box.legendGroup.scrollY = 1;
|
|
2659
|
+
box.legendGroup.css = {
|
|
2660
|
+
flexDirection: (isSide) ? "column" : "row",
|
|
2661
|
+
flexWrap: (isSide) ? "nowrap" : "wrap",
|
|
2662
|
+
alignItems: (isSide) ? "flex-start" : "center",
|
|
2663
|
+
alignSelf: (isSide) ? "center" : "auto",
|
|
2664
|
+
justifyContent: (isPieType() && !isSide) ? "center" : "flex-start",
|
|
2665
|
+
alignContent: "flex-start", // WHY: Lines in the middle of a smaller box: the first ones could not be reached.
|
|
2666
|
+
maxHeight: (isSide) ? "100%" : _s.legend.maxLinesShare,
|
|
2667
|
+
maxWidth: (isSide) ? _s.legend.maxSideShare : "100%",
|
|
2668
|
+
overflowX: "hidden",
|
|
2669
|
+
};
|
|
2670
|
+
|
|
2671
|
+
};
|
|
2672
|
+
|
|
2673
|
+
const toggleLegendItem = function (item) {
|
|
2674
|
+
const entry = item.entry;
|
|
2675
|
+
const setVisible = (isPieType()) ? box.setSliceVisible : box.setDatasetVisible;
|
|
2676
|
+
setVisible(entry.position, entry.isHidden ? 1 : 0);
|
|
2677
|
+
};
|
|
2678
|
+
|
|
2679
|
+
const paintLegendItem = function (item, entry) {
|
|
2680
|
+
item.entry = entry;
|
|
2681
|
+
item.opacity = (entry.isHidden) ? _s.legend.hiddenOpacity : 1;
|
|
2682
|
+
item.aria = { pressed: !entry.isHidden };
|
|
2683
|
+
};
|
|
2684
|
+
|
|
2685
|
+
const createLegendItem = function (entry) {
|
|
2686
|
+
|
|
2687
|
+
// GROUP: One item: its key looks like its mark, its text is never in the data color.
|
|
2688
|
+
const item = HGroup({ hug: 1, gap: _s.legend.keyGap, align: "left center" });
|
|
2689
|
+
item.shrink = 0;
|
|
2690
|
+
|
|
2691
|
+
item.key = Box({ ..._s.legend.keys[entry.keyShape], color: entry.color });
|
|
2692
|
+
item.key.shrink = 0;
|
|
2693
|
+
|
|
2694
|
+
item.label = Label({ plainText: entry.text, fontSize: _s.legend.fontSize, textColor: colors.textColor, css: { whiteSpace: "nowrap" } });
|
|
2695
|
+
|
|
2696
|
+
endGroup();
|
|
2697
|
+
|
|
2698
|
+
item.cursor = "pointer";
|
|
2699
|
+
item.role = "button";
|
|
2700
|
+
item.tabIndex = 0;
|
|
2701
|
+
item.setFocusRing(colors.focusColor);
|
|
2702
|
+
item.on("click", toggleLegendItem);
|
|
2703
|
+
item.on("keydown", function (self, event) {
|
|
2704
|
+
if (event.key !== "Enter" && event.key !== " ") return;
|
|
2705
|
+
event.preventDefault();
|
|
2706
|
+
toggleLegendItem(item);
|
|
2707
|
+
});
|
|
2708
|
+
paintLegendItem(item, entry);
|
|
2709
|
+
|
|
2710
|
+
return item;
|
|
2711
|
+
|
|
2712
|
+
};
|
|
2713
|
+
|
|
2714
|
+
// What makes the objects of the legend different.
|
|
2715
|
+
const getLegendSignature = function (entries) {
|
|
2716
|
+
const parts = entries.map(function (entry) {
|
|
2717
|
+
return [entry.text, entry.color, entry.keyShape, entry.position];
|
|
2718
|
+
});
|
|
2719
|
+
return JSON.stringify(parts) + colors.textColor;
|
|
2720
|
+
};
|
|
2721
|
+
|
|
2722
|
+
const createLegend = function () {
|
|
2723
|
+
|
|
2724
|
+
const entries = getLegendEntries();
|
|
2725
|
+
const signature = getLegendSignature(entries);
|
|
2726
|
+
|
|
2727
|
+
// WHY: Live data: the same legend is not made every second. A hidden item keeps its object: it keeps the focus.
|
|
2728
|
+
if (signature === legendSignature) {
|
|
2729
|
+
box.legendItems.forEach(function (item, itemPlace) {
|
|
2730
|
+
paintLegendItem(item, entries[itemPlace]);
|
|
2731
|
+
});
|
|
2732
|
+
return;
|
|
2733
|
+
}
|
|
2734
|
+
legendSignature = signature;
|
|
2735
|
+
|
|
2736
|
+
box.legendItems.forEach(function (item) { item.remove(); });
|
|
2737
|
+
box.legendItems = entries.map(function (entry) {
|
|
2738
|
+
return createIn(box.legendGroup, function () { return createLegendItem(entry); });
|
|
2739
|
+
});
|
|
2740
|
+
|
|
2741
|
+
};
|
|
2742
|
+
|
|
2743
|
+
// THE TABLE:
|
|
2744
|
+
|
|
2745
|
+
const getPlaceTableData = function () {
|
|
2746
|
+
const series = getVisibleSeries();
|
|
2747
|
+
const rows = [];
|
|
2748
|
+
for (let index = 0; index < getIndexCount(series); index++) {
|
|
2749
|
+
const cells = series.map(function (seriesItem) {
|
|
2750
|
+
const value = getValue(seriesItem.dataset, index);
|
|
2751
|
+
return (value === null) ? "" : formatValueText(value);
|
|
2752
|
+
});
|
|
2753
|
+
rows.push([getLabelText(index)].concat(cells));
|
|
2754
|
+
}
|
|
2755
|
+
const names = series.map(function (seriesItem) { return seriesItem.dataset.label || ""; });
|
|
2756
|
+
return { head: [box.tableHeadText].concat(names), rows: rows };
|
|
2757
|
+
};
|
|
2758
|
+
|
|
2759
|
+
// WHY every small slice one by one: The table is where a value can always be read. Nothing is folded here.
|
|
2760
|
+
const getTableSlices = function () {
|
|
2761
|
+
const parts = splitSlices();
|
|
2762
|
+
const kept = parts.kept.filter(function (slice) { return !isSliceHidden(slice.index); });
|
|
2763
|
+
const folded = (isSliceHidden(GraphBox.OTHER_SLICE)) ? [] : parts.folded;
|
|
2764
|
+
return kept.concat(folded).sort(function (first, second) { return first.index - second.index; });
|
|
2765
|
+
};
|
|
2766
|
+
|
|
2767
|
+
const getSliceTableData = function () {
|
|
2768
|
+
const slices = getTableSlices();
|
|
2769
|
+
const total = getTotal(slices);
|
|
2770
|
+
const dataset = box.data.datasets[0];
|
|
2771
|
+
const rows = slices.map(function (slice) {
|
|
2772
|
+
return [getLabelText(slice.index), formatValueText(slice.value), GraphBox.formatPercent(slice.value / total, box.locale)];
|
|
2773
|
+
});
|
|
2774
|
+
return { head: [box.tableHeadText, (dataset && dataset.label) || "", "%"], rows: rows };
|
|
2775
|
+
};
|
|
2776
|
+
|
|
2777
|
+
const getPointTableData = function () {
|
|
2778
|
+
const isBubble = (box.type === "bubble");
|
|
2779
|
+
const rows = createScatterPoints(getVisibleSeries()).map(function (point) {
|
|
2780
|
+
const name = (point.label === undefined) ? point.seriesName : String(point.label);
|
|
2781
|
+
const cells = [name, formatXText(point.x), formatValueText(point.y)];
|
|
2782
|
+
if (isBubble) cells.push((point.size === null) ? "" : GraphBox.formatNumber(point.size, box.locale));
|
|
2783
|
+
return cells;
|
|
2784
|
+
});
|
|
2785
|
+
const head = [box.tableHeadText, box.xAxisText || "x", box.yAxisText || "y"];
|
|
2786
|
+
if (isBubble) head.push(box.sizeText);
|
|
2787
|
+
return { head: head, rows: rows };
|
|
2788
|
+
};
|
|
2789
|
+
|
|
2790
|
+
const createTableRow = function (cells, isHead) {
|
|
2791
|
+
|
|
2792
|
+
const row = HGroup({ width: "100%", height: _s.table.rowHeight, align: "left center" });
|
|
2793
|
+
row.shrink = 0;
|
|
2794
|
+
row.role = "row";
|
|
2795
|
+
row.css = { borderBottom: "1px solid " + colors.gridColor };
|
|
2796
|
+
|
|
2797
|
+
cells.forEach(function (cell, cellIndex) {
|
|
2798
|
+
const label = Label({
|
|
2799
|
+
plainText: cell,
|
|
2800
|
+
width: "auto",
|
|
2801
|
+
fontSize: _s.table.fontSize,
|
|
2802
|
+
textColor: (cellIndex === 0 || isHead) ? colors.titleColor : colors.textColor,
|
|
2803
|
+
ellipsis: 1,
|
|
2804
|
+
role: (isHead) ? "columnheader" : "cell",
|
|
2805
|
+
css: {
|
|
2806
|
+
flex: "1 1 0",
|
|
2807
|
+
minWidth: "0px",
|
|
2808
|
+
padding: "0px " + _s.table.cellPadding + "px",
|
|
2809
|
+
textAlign: (cellIndex === 0) ? "left" : "right",
|
|
2810
|
+
fontVariantNumeric: "tabular-nums", // WHY: The digits of a column stand under each other.
|
|
2811
|
+
},
|
|
2812
|
+
});
|
|
2813
|
+
if (isHead) label.fontFamily = _s.table.headFontFamily;
|
|
2814
|
+
});
|
|
2815
|
+
|
|
2816
|
+
endGroup();
|
|
2817
|
+
|
|
2818
|
+
};
|
|
2819
|
+
|
|
2820
|
+
const createTable = function () {
|
|
2821
|
+
|
|
2822
|
+
const oldScroll = (box.tableBox) ? box.tableBox.elem.scrollTop : 0;
|
|
2823
|
+
if (box.tableBox) box.tableBox.remove();
|
|
2824
|
+
box.tableBox = null;
|
|
2825
|
+
if (box.tableView != 1) return;
|
|
2826
|
+
|
|
2827
|
+
const tableData = box.getTableData();
|
|
2828
|
+
|
|
2829
|
+
box.tableBox = createIn(box.body, function () {
|
|
2830
|
+
const group = VGroup({ width: "100%", height: "auto", align: "left top", scrollY: 1, role: "table" });
|
|
2831
|
+
createTableRow(tableData.head, 1);
|
|
2832
|
+
tableData.rows.forEach(function (cells) { createTableRow(cells, 0); });
|
|
2833
|
+
endGroup();
|
|
2834
|
+
return group;
|
|
2835
|
+
});
|
|
2836
|
+
box.tableBox.css = { flex: "1 1 0", minHeight: "0px", alignSelf: "stretch" };
|
|
2837
|
+
box.tableBox.aria = { label: box.titleText || box.type + " chart" };
|
|
2838
|
+
box.tableBox.elem.scrollTop = oldScroll; // WHY: A live chart makes its table again every second.
|
|
2839
|
+
|
|
2840
|
+
};
|
|
2841
|
+
|
|
2842
|
+
// WHY drawn again: The data may have changed while the plot was hidden.
|
|
2843
|
+
const applyTableView = function () {
|
|
2844
|
+
if (box.tableView == 1) clearActiveItem();
|
|
2845
|
+
refreshLayout();
|
|
2846
|
+
createTable();
|
|
2847
|
+
};
|
|
2848
|
+
|
|
2849
|
+
// THE IMAGE:
|
|
2850
|
+
// WHY a canvas, not the SVG in a picture: An SVG in a picture can not use the fonts of the page, so every text would
|
|
2851
|
+
// change and it would not fit its room. Here every shape is painted again from its own attributes.
|
|
2852
|
+
|
|
2853
|
+
const applyRotation = function (context, shape) {
|
|
2854
|
+
const match = /rotate\((-?[\d.]+) (-?[\d.]+) (-?[\d.]+)\)/.exec(shape.getAttribute("transform") || "");
|
|
2855
|
+
if (!match) return;
|
|
2856
|
+
const x = Number(match[2]);
|
|
2857
|
+
const y = Number(match[3]);
|
|
2858
|
+
context.translate(x, y);
|
|
2859
|
+
context.rotate(Number(match[1]) * Math.PI / 180);
|
|
2860
|
+
context.translate(-x, -y);
|
|
2861
|
+
};
|
|
2862
|
+
|
|
2863
|
+
const paintImageText = function (context, shape) {
|
|
2864
|
+
context.save();
|
|
2865
|
+
applyRotation(context, shape);
|
|
2866
|
+
const fontSize = shape.getAttribute("font-size") || _s.axis.fontSize;
|
|
2867
|
+
const fontFamily = shape.getAttribute("font-family") || _s.axis.fontFamily;
|
|
2868
|
+
context.font = fontSize + "px " + fontFamily;
|
|
2869
|
+
context.textAlign = { start: "left", middle: "center", end: "right" }[shape.getAttribute("text-anchor")];
|
|
2870
|
+
context.textBaseline = "middle";
|
|
2871
|
+
const x = Number(shape.getAttribute("x"));
|
|
2872
|
+
const y = Number(shape.getAttribute("y"));
|
|
2873
|
+
if (shape.getAttribute("stroke")) {
|
|
2874
|
+
context.strokeStyle = shape.getAttribute("stroke");
|
|
2875
|
+
context.lineWidth = Number(shape.getAttribute("stroke-width")) || 1;
|
|
2876
|
+
context.strokeText(shape.textContent, x, y);
|
|
2877
|
+
}
|
|
2878
|
+
context.fillStyle = shape.getAttribute("fill");
|
|
2879
|
+
context.fillText(shape.textContent, x, y);
|
|
2880
|
+
context.restore();
|
|
2881
|
+
};
|
|
2882
|
+
|
|
2883
|
+
const createImagePath = function (shape, name) {
|
|
2884
|
+
const path = new Path2D();
|
|
2885
|
+
const read = function (key) { return Number(shape.getAttribute(key)); };
|
|
2886
|
+
if (name === "path") return new Path2D(shape.getAttribute("d"));
|
|
2887
|
+
if (name === "line") {
|
|
2888
|
+
path.moveTo(read("x1"), read("y1"));
|
|
2889
|
+
path.lineTo(read("x2"), read("y2"));
|
|
2890
|
+
}
|
|
2891
|
+
if (name === "rect") path.rect(read("x"), read("y"), read("width"), read("height"));
|
|
2892
|
+
if (name === "circle") path.arc(read("cx"), read("cy"), read("r"), 0, FULL_CIRCLE);
|
|
2893
|
+
return path;
|
|
2894
|
+
};
|
|
2895
|
+
|
|
2896
|
+
// A fill: a color, or a gradient of the SVG made again for the canvas.
|
|
2897
|
+
const getImageFill = function (context, shape) {
|
|
2898
|
+
const fill = shape.getAttribute("fill");
|
|
2899
|
+
const match = /^url\(#(.+)\)$/.exec(fill || "");
|
|
2900
|
+
if (!match) return fill;
|
|
2901
|
+
const shapeBox = shape.getBBox();
|
|
2902
|
+
const gradient = context.createLinearGradient(0, shapeBox.y, 0, shapeBox.y + shapeBox.height);
|
|
2903
|
+
svg.getElementById(match[1]).querySelectorAll("stop").forEach(function (stop) {
|
|
2904
|
+
const color = GraphBox.toTransparent(stop.getAttribute("stop-color"), stop.getAttribute("stop-opacity"));
|
|
2905
|
+
gradient.addColorStop(Number(stop.getAttribute("offset")), color);
|
|
2906
|
+
});
|
|
2907
|
+
return gradient;
|
|
2908
|
+
};
|
|
2909
|
+
|
|
2910
|
+
const paintImageShape = function (context, shape, name) {
|
|
2911
|
+
|
|
2912
|
+
const path = createImagePath(shape, name);
|
|
2913
|
+
const fill = getImageFill(context, shape);
|
|
2914
|
+
const stroke = shape.getAttribute("stroke");
|
|
2915
|
+
const dash = shape.getAttribute("stroke-dasharray");
|
|
2916
|
+
|
|
2917
|
+
const paintFill = function () {
|
|
2918
|
+
if (!fill || fill === "none") return;
|
|
2919
|
+
context.globalAlpha = Number(shape.getAttribute("fill-opacity") || 1);
|
|
2920
|
+
context.fillStyle = fill;
|
|
2921
|
+
context.fill(path, "nonzero");
|
|
2922
|
+
context.globalAlpha = 1;
|
|
2923
|
+
};
|
|
2924
|
+
|
|
2925
|
+
const paintStroke = function () {
|
|
2926
|
+
if (!stroke || stroke === "none") return;
|
|
2927
|
+
context.strokeStyle = stroke;
|
|
2928
|
+
context.lineWidth = Number(shape.getAttribute("stroke-width")) || 1;
|
|
2929
|
+
context.lineCap = shape.getAttribute("stroke-linecap") || "butt";
|
|
2930
|
+
context.lineJoin = shape.getAttribute("stroke-linejoin") || "miter";
|
|
2931
|
+
context.setLineDash((dash && dash !== "none") ? dash.split(" ").map(Number) : []);
|
|
2932
|
+
context.stroke(path);
|
|
2933
|
+
context.setLineDash([]);
|
|
2934
|
+
};
|
|
2935
|
+
|
|
2936
|
+
if (shape.getAttribute("paint-order") === "stroke") {
|
|
2937
|
+
paintStroke();
|
|
2938
|
+
paintFill();
|
|
2939
|
+
return;
|
|
2940
|
+
}
|
|
2941
|
+
paintFill();
|
|
2942
|
+
paintStroke();
|
|
2943
|
+
|
|
2944
|
+
};
|
|
2945
|
+
|
|
2946
|
+
const applyImageClip = function (context, layer) {
|
|
2947
|
+
const match = /^url\(#(.+)\)$/.exec(layer.getAttribute("clip-path") || "");
|
|
2948
|
+
if (!match) return;
|
|
2949
|
+
const rect = svg.getElementById(match[1]).querySelector("rect");
|
|
2950
|
+
const read = function (key) { return Number(rect.getAttribute(key)); };
|
|
2951
|
+
context.beginPath();
|
|
2952
|
+
context.rect(read("x"), read("y"), read("width"), read("height"));
|
|
2953
|
+
context.clip();
|
|
2954
|
+
};
|
|
2955
|
+
|
|
2956
|
+
const paintImageLayer = function (context, layer) {
|
|
2957
|
+
context.save();
|
|
2958
|
+
applyImageClip(context, layer);
|
|
2959
|
+
Array.from(layer.children).forEach(function (shape) {
|
|
2960
|
+
const name = shape.tagName.toLowerCase();
|
|
2961
|
+
if (name === "g") paintImageLayer(context, shape);
|
|
2962
|
+
else if (name === "text") paintImageText(context, shape);
|
|
2963
|
+
else paintImageShape(context, shape, name);
|
|
2964
|
+
});
|
|
2965
|
+
context.restore();
|
|
2966
|
+
};
|
|
2967
|
+
|
|
2968
|
+
// The place of an object in the card, in px of the card.
|
|
2969
|
+
const getPlaceInBox = function (object) {
|
|
2970
|
+
const boxRect = box.elem.getBoundingClientRect();
|
|
2971
|
+
const rect = object.elem.getBoundingClientRect();
|
|
2972
|
+
const zoom = getZoom(box.elem, boxRect);
|
|
2973
|
+
return {
|
|
2974
|
+
left: (rect.left - boxRect.left) / zoom,
|
|
2975
|
+
top: (rect.top - boxRect.top) / zoom,
|
|
2976
|
+
width: rect.width / zoom,
|
|
2977
|
+
height: rect.height / zoom,
|
|
2978
|
+
};
|
|
2979
|
+
};
|
|
2980
|
+
|
|
2981
|
+
const paintImageLabel = function (context, label, opacity = 1) {
|
|
2982
|
+
if (label.visible != 1 || !label.elem.textContent) return;
|
|
2983
|
+
const place = getPlaceInBox(label);
|
|
2984
|
+
const style = getComputedStyle(label.elem);
|
|
2985
|
+
context.font = style.fontSize + " " + style.fontFamily;
|
|
2986
|
+
context.fillStyle = style.color;
|
|
2987
|
+
context.textAlign = "left";
|
|
2988
|
+
context.textBaseline = "middle";
|
|
2989
|
+
context.globalAlpha = opacity;
|
|
2990
|
+
const lines = GraphBox.wrapText(context, label.elem.textContent, place.width);
|
|
2991
|
+
const lineHeight = place.height / lines.length;
|
|
2992
|
+
lines.forEach(function (line, linePlace) {
|
|
2993
|
+
context.fillText(line, place.left, place.top + lineHeight * (linePlace + 0.5));
|
|
2994
|
+
});
|
|
2995
|
+
context.globalAlpha = 1;
|
|
2996
|
+
};
|
|
2997
|
+
|
|
2998
|
+
const paintImageCard = function (context, width, height) {
|
|
2999
|
+
const surfaceColor = getSurfaceColor();
|
|
3000
|
+
const border = Number(box.border) || 0;
|
|
3001
|
+
const round = Number(box.round) || 0;
|
|
3002
|
+
context.beginPath();
|
|
3003
|
+
if (context.roundRect) context.roundRect(border / 2, border / 2, width - border, height - border, round);
|
|
3004
|
+
else context.rect(border / 2, border / 2, width - border, height - border);
|
|
3005
|
+
if (surfaceColor !== "transparent") {
|
|
3006
|
+
context.fillStyle = surfaceColor;
|
|
3007
|
+
context.fill();
|
|
3008
|
+
}
|
|
3009
|
+
if (!border) return;
|
|
3010
|
+
context.strokeStyle = box.borderColor;
|
|
3011
|
+
context.lineWidth = border;
|
|
3012
|
+
context.stroke();
|
|
3013
|
+
};
|
|
3014
|
+
|
|
3015
|
+
const paintImageLegend = function (context) {
|
|
3016
|
+
if (box.legendGroup.visible != 1) return;
|
|
3017
|
+
box.legendItems.forEach(function (item) {
|
|
3018
|
+
const place = getPlaceInBox(item.key);
|
|
3019
|
+
context.globalAlpha = Number(item.opacity);
|
|
3020
|
+
context.fillStyle = item.key.color;
|
|
3021
|
+
context.beginPath();
|
|
3022
|
+
if (context.roundRect) context.roundRect(place.left, place.top, place.width, place.height, Number(item.key.round) || 0);
|
|
3023
|
+
else context.rect(place.left, place.top, place.width, place.height);
|
|
3024
|
+
context.fill();
|
|
3025
|
+
context.globalAlpha = 1;
|
|
3026
|
+
paintImageLabel(context, item.label, Number(item.opacity));
|
|
3027
|
+
});
|
|
3028
|
+
};
|
|
3029
|
+
|
|
3030
|
+
// THE LOOK AND THE TEXTS:
|
|
3031
|
+
|
|
3032
|
+
const applyLook = function () {
|
|
3033
|
+
colors = Object.assign(basic.resolveTheme(GraphBox.THEMES, box.theme), _s.colors);
|
|
3034
|
+
box.color = getSurfaceColor();
|
|
3035
|
+
box.border = _s.box.border;
|
|
3036
|
+
box.borderColor = _s.box.borderColor || colors.borderColor;
|
|
3037
|
+
box.round = _s.box.round;
|
|
3038
|
+
box.layout.gap = _s.box.gap;
|
|
3039
|
+
box.layout.css = { padding: _s.box.padding + "px" };
|
|
3040
|
+
box.body.gap = _s.box.gap;
|
|
3041
|
+
box.lblTitle.textColor = colors.titleColor;
|
|
3042
|
+
box.lblSubtitle.textColor = colors.textColor;
|
|
3043
|
+
box.lblEmpty.textColor = colors.mutedTextColor;
|
|
3044
|
+
box.tooltip.color = colors.tooltipColor;
|
|
3045
|
+
box.lblTooltipTitle.textColor = colors.tooltipMutedColor;
|
|
3046
|
+
box.plot.setFocusRing(colors.focusColor);
|
|
3047
|
+
};
|
|
3048
|
+
|
|
3049
|
+
const applyContent = function () {
|
|
3050
|
+
box.lblTitle.plainText = box.titleText;
|
|
3051
|
+
box.lblTitle.visible = (box.titleText) ? 1 : 0;
|
|
3052
|
+
box.lblSubtitle.plainText = box.subtitleText;
|
|
3053
|
+
box.lblSubtitle.visible = (box.subtitleText) ? 1 : 0;
|
|
3054
|
+
box.texts.visible = (box.titleText || box.subtitleText) ? 1 : 0;
|
|
3055
|
+
applySummary();
|
|
3056
|
+
};
|
|
3057
|
+
|
|
3058
|
+
const refreshLayout = function () {
|
|
3059
|
+
applyLegendPosition();
|
|
3060
|
+
box.plot.visible = (box.tableView == 1) ? 0 : 1;
|
|
3061
|
+
drawPlot();
|
|
3062
|
+
};
|
|
3063
|
+
|
|
3064
|
+
// WHY: A page can change box.data by hand before box.update().
|
|
3065
|
+
const prepareData = function () {
|
|
3066
|
+
if (!box.data.labels) box.data.labels = [];
|
|
3067
|
+
if (!box.data.datasets) box.data.datasets = [];
|
|
3068
|
+
box.data.datasets.forEach(function (dataset) {
|
|
3069
|
+
if (!dataset.data) dataset.data = [];
|
|
3070
|
+
});
|
|
3071
|
+
};
|
|
3072
|
+
|
|
3073
|
+
const drawData = function () {
|
|
3074
|
+
isChangeWaiting = 1;
|
|
3075
|
+
prepareData();
|
|
3076
|
+
assignColors();
|
|
3077
|
+
createLegend();
|
|
3078
|
+
refreshLayout();
|
|
3079
|
+
createTable();
|
|
3080
|
+
};
|
|
3081
|
+
|
|
3082
|
+
const drawAll = function () {
|
|
3083
|
+
applyLook();
|
|
3084
|
+
applyContent();
|
|
3085
|
+
drawData();
|
|
3086
|
+
};
|
|
3087
|
+
|
|
3088
|
+
const onPlotResize = function () {
|
|
3089
|
+
const size = box.plot.elem.clientWidth + "x" + box.plot.elem.clientHeight;
|
|
3090
|
+
if (size !== drawnSize) drawPlot(); // WHY: The observer also runs once when it starts.
|
|
3091
|
+
// WHY later: Moving the legend changes the size of the plot, and an observer must not change what it watches
|
|
3092
|
+
// while it runs (the browser reports it as an error of the page).
|
|
3093
|
+
if (getLegendPosition() !== legendPlace) box.after(0, refreshLayout);
|
|
3094
|
+
};
|
|
3095
|
+
|
|
3096
|
+
const onSystemThemeChange = function () {
|
|
3097
|
+
if (box.theme === "auto") drawAll();
|
|
3098
|
+
};
|
|
3099
|
+
|
|
3100
|
+
// WHY: The first measures can be made before the font of the kit is loaded, then the axis has the wrong room.
|
|
3101
|
+
const redrawWhenFontIsLoaded = function () {
|
|
3102
|
+
const font = _s.axis.fontSize + "px opensans";
|
|
3103
|
+
if (!document.fonts || document.fonts.check(font)) return;
|
|
3104
|
+
const redraw = function () {
|
|
3105
|
+
if (!box._isRemoved) drawPlot();
|
|
3106
|
+
};
|
|
3107
|
+
document.fonts.load(font).then(redraw, redraw);
|
|
3108
|
+
};
|
|
3109
|
+
|
|
3110
|
+
// *** PUBLIC FUNCTIONS:
|
|
3111
|
+
|
|
3112
|
+
// WHY: The same as ChartBox, so a page can move over. Here it runs at once: nothing is loaded.
|
|
3113
|
+
box.whenReady = function (func) {
|
|
3114
|
+
func(box);
|
|
3115
|
+
};
|
|
3116
|
+
|
|
3117
|
+
// Redraw after the data changed. Ex: box.data.datasets[0].data[2] = 50; box.update();
|
|
3118
|
+
box.update = function () {
|
|
3119
|
+
drawData();
|
|
3120
|
+
};
|
|
3121
|
+
|
|
3122
|
+
box.setData = function (data) {
|
|
3123
|
+
box.data = copyData(data);
|
|
3124
|
+
drawData();
|
|
3125
|
+
};
|
|
3126
|
+
// USAGE: graph.setData({ labels: ["A", "B"], datasets: [{ label: "X", data: [1, 2] }] })
|
|
3127
|
+
|
|
3128
|
+
box.setLabels = function (labels) {
|
|
3129
|
+
box.data.labels = (labels || []).slice();
|
|
3130
|
+
drawData();
|
|
3131
|
+
};
|
|
3132
|
+
|
|
3133
|
+
box.setDatasets = function (datasets) {
|
|
3134
|
+
box.data.datasets = (datasets || []).map(copyDataset);
|
|
3135
|
+
drawData();
|
|
3136
|
+
};
|
|
3137
|
+
|
|
3138
|
+
// Change the values of one dataset. The dataset is created, if it is not there.
|
|
3139
|
+
box.setValues = function (values, datasetIndex = 0) {
|
|
3140
|
+
const dataset = box.data.datasets[datasetIndex];
|
|
3141
|
+
if (!dataset) {
|
|
3142
|
+
box.addDataset({ data: values });
|
|
3143
|
+
return;
|
|
3144
|
+
}
|
|
3145
|
+
dataset.data = (values || []).slice();
|
|
3146
|
+
drawData();
|
|
3147
|
+
};
|
|
3148
|
+
|
|
3149
|
+
// Add a new label and values to the end. (For live data, use maxCount.)
|
|
3150
|
+
box.addValue = function (label, values) {
|
|
3151
|
+
|
|
3152
|
+
const list = (Array.isArray(values)) ? values : [values];
|
|
3153
|
+
const datasets = box.data.datasets;
|
|
3154
|
+
|
|
3155
|
+
let removedCount = 0;
|
|
3156
|
+
if (box.maxCount > 0) {
|
|
3157
|
+
while (box.data.labels.length >= box.maxCount) {
|
|
3158
|
+
box.data.labels.shift();
|
|
3159
|
+
datasets.forEach(function (dataset) { dataset.data.shift(); });
|
|
3160
|
+
removedCount++;
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
addedValueShift = removedCount;
|
|
3164
|
+
|
|
3165
|
+
box.data.labels.push(label);
|
|
3166
|
+
datasets.forEach(function (dataset, position) {
|
|
3167
|
+
dataset.data.push((list[position] !== undefined) ? list[position] : null);
|
|
3168
|
+
});
|
|
3169
|
+
|
|
3170
|
+
drawData();
|
|
3171
|
+
|
|
3172
|
+
};
|
|
3173
|
+
// USAGE: graph.addValue("May", 42) or graph.addValue("May", [42, 30]) (one value for each dataset)
|
|
3174
|
+
|
|
3175
|
+
// scatter, bubble: Add a point to a dataset.
|
|
3176
|
+
box.addPoint = function (point, datasetIndex = 0) {
|
|
3177
|
+
const dataset = box.data.datasets[datasetIndex];
|
|
3178
|
+
if (!dataset) return;
|
|
3179
|
+
if (box.maxCount > 0 && dataset.data.length >= box.maxCount) dataset.data.shift();
|
|
3180
|
+
dataset.data.push(point);
|
|
3181
|
+
drawData();
|
|
3182
|
+
};
|
|
3183
|
+
// USAGE: graph.addPoint({ x: 170, y: 65 }, 0)
|
|
3184
|
+
|
|
3185
|
+
box.addDataset = function (dataset) {
|
|
3186
|
+
box.data.datasets.push(copyDataset(dataset));
|
|
3187
|
+
drawData();
|
|
3188
|
+
};
|
|
3189
|
+
|
|
3190
|
+
box.removeDataset = function (position) {
|
|
3191
|
+
if (position < 0 || position >= box.data.datasets.length) return;
|
|
3192
|
+
box.data.datasets.splice(position, 1);
|
|
3193
|
+
drawData();
|
|
3194
|
+
};
|
|
3195
|
+
|
|
3196
|
+
box.setDatasetVisible = function (position, visible) {
|
|
3197
|
+
const dataset = box.data.datasets[position];
|
|
3198
|
+
if (!dataset) return;
|
|
3199
|
+
dataset.hidden = (basic.isOn(visible)) ? 0 : 1;
|
|
3200
|
+
drawData();
|
|
3201
|
+
};
|
|
3202
|
+
|
|
3203
|
+
// Hide or show a slice of a pie or a doughnut. (index: GraphBox.OTHER_SLICE: the "Other" slice)
|
|
3204
|
+
box.setSliceVisible = function (index, visible) {
|
|
3205
|
+
const key = getSliceKey(index);
|
|
3206
|
+
if (basic.isOn(visible)) hiddenSliceKeys.delete(key);
|
|
3207
|
+
else hiddenSliceKeys.add(key);
|
|
3208
|
+
drawData();
|
|
3209
|
+
};
|
|
3210
|
+
|
|
3211
|
+
box.setType = function (type) {
|
|
3212
|
+
box.type = type;
|
|
3213
|
+
drawData();
|
|
3214
|
+
};
|
|
3215
|
+
// USAGE: "line", "area", "bar", "pie", "doughnut", "radar", "scatter", "bubble"
|
|
3216
|
+
|
|
3217
|
+
// The texts in the middle of a doughnut.
|
|
3218
|
+
box.setCenterText = function (text, subText = box.centerSubText) {
|
|
3219
|
+
box.centerText = text;
|
|
3220
|
+
box.centerSubText = subText;
|
|
3221
|
+
drawPlot();
|
|
3222
|
+
};
|
|
3223
|
+
|
|
3224
|
+
box.setTitleText = function (text) {
|
|
3225
|
+
box.titleText = text;
|
|
3226
|
+
applyContent();
|
|
3227
|
+
};
|
|
3228
|
+
|
|
3229
|
+
box.setSubtitleText = function (text) {
|
|
3230
|
+
box.subtitleText = text;
|
|
3231
|
+
applyContent();
|
|
3232
|
+
};
|
|
3233
|
+
|
|
3234
|
+
box.setLegend = function (legend) {
|
|
3235
|
+
box.legend = legend;
|
|
3236
|
+
refreshLayout();
|
|
3237
|
+
};
|
|
3238
|
+
// USAGE: "auto", "top", "bottom", "left", "right", "none"
|
|
3239
|
+
|
|
3240
|
+
box.setShowValues = function (value) {
|
|
3241
|
+
box.showValues = (basic.isOn(value)) ? 1 : 0;
|
|
3242
|
+
drawPlot();
|
|
3243
|
+
};
|
|
3244
|
+
|
|
3245
|
+
// The table of the values in place of the chart.
|
|
3246
|
+
box.setTableView = function (value) {
|
|
3247
|
+
box.tableView = (basic.isOn(value)) ? 1 : 0;
|
|
3248
|
+
applyTableView();
|
|
3249
|
+
};
|
|
3250
|
+
// USAGE: graph.setTableView(graph.tableView ? 0 : 1)
|
|
3251
|
+
|
|
3252
|
+
// The values as texts, the same as the tooltip: { head: ["", "2025", "2026"], rows: [["Q1", "12", "15"], ...] }
|
|
3253
|
+
box.getTableData = function () {
|
|
3254
|
+
if (isPieType()) return getSliceTableData();
|
|
3255
|
+
if (isScatterType()) return getPointTableData();
|
|
3256
|
+
return getPlaceTableData();
|
|
3257
|
+
};
|
|
3258
|
+
|
|
3259
|
+
// The whole card on a new canvas. scale: 2: sharp on every screen.
|
|
3260
|
+
box.getCanvas = function (scale = 2) {
|
|
3261
|
+
|
|
3262
|
+
const width = box.elem.offsetWidth;
|
|
3263
|
+
const height = box.elem.offsetHeight;
|
|
3264
|
+
const canvas = document.createElement("canvas");
|
|
3265
|
+
canvas.width = width * scale;
|
|
3266
|
+
canvas.height = height * scale;
|
|
3267
|
+
|
|
3268
|
+
const context = canvas.getContext("2d");
|
|
3269
|
+
context.scale(scale, scale);
|
|
3270
|
+
paintImageCard(context, width, height);
|
|
3271
|
+
paintImageLabel(context, box.lblTitle);
|
|
3272
|
+
paintImageLabel(context, box.lblSubtitle);
|
|
3273
|
+
paintImageLegend(context);
|
|
3274
|
+
|
|
3275
|
+
const plotPlace = getPlaceInBox(box.plot);
|
|
3276
|
+
context.translate(plotPlace.left, plotPlace.top);
|
|
3277
|
+
[gridLayer, washLayer, clipLayer, overlayLayer, valueLayer].forEach(function (layer) {
|
|
3278
|
+
paintImageLayer(context, layer);
|
|
3279
|
+
});
|
|
3280
|
+
|
|
3281
|
+
return canvas;
|
|
3282
|
+
|
|
3283
|
+
};
|
|
3284
|
+
|
|
3285
|
+
// The picture of the card. (Data URL)
|
|
3286
|
+
box.getImage = function (imageType = "image/png", scale = 2) {
|
|
3287
|
+
const canvas = box.getCanvas(scale);
|
|
3288
|
+
if (imageType === "image/jpeg") {
|
|
3289
|
+
// WHY: A JPEG has no transparent pixels: the round corners of the card would be black.
|
|
3290
|
+
const context = canvas.getContext("2d");
|
|
3291
|
+
context.setTransform(1, 0, 0, 1, 0, 0);
|
|
3292
|
+
context.globalCompositeOperation = "destination-over";
|
|
3293
|
+
context.fillStyle = "#FFFFFF";
|
|
3294
|
+
context.fillRect(0, 0, canvas.width, canvas.height);
|
|
3295
|
+
}
|
|
3296
|
+
return canvas.toDataURL(imageType);
|
|
3297
|
+
};
|
|
3298
|
+
|
|
3299
|
+
box.download = function (fileName = "chart.png") {
|
|
3300
|
+
const isJpeg = fileName.toLowerCase().endsWith(".jpg");
|
|
3301
|
+
const link = document.createElement("a");
|
|
3302
|
+
link.href = box.getImage((isJpeg) ? "image/jpeg" : "image/png");
|
|
3303
|
+
link.download = fileName;
|
|
3304
|
+
link.click();
|
|
3305
|
+
};
|
|
3306
|
+
// USAGE: graph.download("sales.png")
|
|
3307
|
+
|
|
3308
|
+
box.setTargetLines = function (lines) {
|
|
3309
|
+
box.targetLines = (lines || []).slice();
|
|
3310
|
+
drawChange();
|
|
3311
|
+
};
|
|
3312
|
+
// USAGE: graph.setTargetLines([{ value: 90000, label: "Target" }, { value: 20000, label: "Limit", color: "tomato" }])
|
|
3313
|
+
|
|
3314
|
+
box.setMaxSlices = function (count) {
|
|
3315
|
+
box.maxSlices = count;
|
|
3316
|
+
drawData();
|
|
3317
|
+
};
|
|
3318
|
+
// USAGE: graph.setMaxSlices(6) / graph.setMaxSlices(0) // every slice alone
|
|
3319
|
+
|
|
3320
|
+
box.setStacked = function (stacked) {
|
|
3321
|
+
box.stacked = (basic.isOn(stacked)) ? 1 : 0;
|
|
3322
|
+
drawChange();
|
|
3323
|
+
};
|
|
3324
|
+
|
|
3325
|
+
box.setHorizontal = function (horizontal) {
|
|
3326
|
+
box.horizontal = (basic.isOn(horizontal)) ? 1 : 0;
|
|
3327
|
+
drawChange();
|
|
3328
|
+
};
|
|
3329
|
+
|
|
3330
|
+
box.setAnimated = function (value) {
|
|
3331
|
+
box.animated = (basic.isOn(value)) ? 1 : 0;
|
|
3332
|
+
if (box.animated == 1) return;
|
|
3333
|
+
// WHY: The tooltip goes back to left and top, with no transform and no transition.
|
|
3334
|
+
box.tooltip.setMotionNow("");
|
|
3335
|
+
box.tooltip.css = { transform: "" };
|
|
3336
|
+
box.tooltip.opacity = 1;
|
|
3337
|
+
box.tooltip.visible = (isTooltipShown) ? 1 : 0;
|
|
3338
|
+
if (isTooltipShown) placeTooltip();
|
|
3339
|
+
};
|
|
3340
|
+
// USAGE: graph.setAnimated(1)
|
|
3341
|
+
|
|
3342
|
+
box.setCurve = function (curve) {
|
|
3343
|
+
box.curve = curve;
|
|
3344
|
+
drawChange();
|
|
3345
|
+
};
|
|
3346
|
+
|
|
3347
|
+
// The limits of the value axis. null: from the values.
|
|
3348
|
+
box.setValueLimits = function (minValue, maxValue) {
|
|
3349
|
+
box.minValue = minValue;
|
|
3350
|
+
box.maxValue = maxValue;
|
|
3351
|
+
drawChange();
|
|
3352
|
+
};
|
|
3353
|
+
|
|
3354
|
+
// The axis goes at least this far, more if a value needs it. null: from the values.
|
|
3355
|
+
box.setSoftLimits = function (softMinValue, softMaxValue) {
|
|
3356
|
+
box.softMinValue = softMinValue;
|
|
3357
|
+
box.softMaxValue = softMaxValue;
|
|
3358
|
+
drawChange();
|
|
3359
|
+
};
|
|
3360
|
+
|
|
3361
|
+
box.setValueStep = function (step) {
|
|
3362
|
+
box.valueStep = step;
|
|
3363
|
+
drawChange();
|
|
3364
|
+
};
|
|
3365
|
+
|
|
3366
|
+
// scatter, bubble: The limits of the x axis. null: from the values.
|
|
3367
|
+
box.setXLimits = function (minX, maxX) {
|
|
3368
|
+
box.minX = minX;
|
|
3369
|
+
box.maxX = maxX;
|
|
3370
|
+
drawPlot();
|
|
3371
|
+
};
|
|
3372
|
+
|
|
3373
|
+
box.setAxisTexts = function (xAxisText, yAxisText) {
|
|
3374
|
+
box.xAxisText = xAxisText;
|
|
3375
|
+
box.yAxisText = yAxisText;
|
|
3376
|
+
drawPlot();
|
|
3377
|
+
};
|
|
3378
|
+
|
|
3379
|
+
box.setFormatValue = function (func) {
|
|
3380
|
+
box.formatValue = func;
|
|
3381
|
+
drawPlot();
|
|
3382
|
+
};
|
|
3383
|
+
|
|
3384
|
+
box.setFormatX = function (func) {
|
|
3385
|
+
box.formatX = func;
|
|
3386
|
+
drawPlot();
|
|
3387
|
+
};
|
|
3388
|
+
|
|
3389
|
+
box.setTheme = function (theme) {
|
|
3390
|
+
box.theme = theme;
|
|
3391
|
+
drawAll();
|
|
3392
|
+
};
|
|
3393
|
+
// USAGE: "light", "dark", "auto", "minimal", "minimalDark"
|
|
3394
|
+
// NOTE: It changes the colors. The shapes of a theme (minimal) come when the chart is created.
|
|
3395
|
+
|
|
3396
|
+
// Change some values of the style. Ex: setStyle({ colors: { gridColor: "#334155" }, box: { round: 0 } })
|
|
3397
|
+
box.setStyle = function (style) {
|
|
3398
|
+
const merged = {};
|
|
3399
|
+
mergeIntoIfMissing(merged, style);
|
|
3400
|
+
mergeIntoIfMissing(merged, _s);
|
|
3401
|
+
box.style = merged;
|
|
3402
|
+
_s = merged;
|
|
3403
|
+
legendSignature = ""; // WHY: The sizes of the legend are in the style too.
|
|
3404
|
+
drawAll();
|
|
3405
|
+
};
|
|
3406
|
+
|
|
3407
|
+
// *** OBJECT VIEW:
|
|
3408
|
+
|
|
3409
|
+
// GROUP: Layout (the texts, then the legend and the chart)
|
|
3410
|
+
box.layout = VGroup({ align: "left top", gap: _s.box.gap, padding: _s.box.padding });
|
|
3411
|
+
|
|
3412
|
+
// GROUP: Texts
|
|
3413
|
+
box.texts = VGroup({ width: "100%", height: "auto", align: "left top", gap: 2 });
|
|
3414
|
+
box.texts.shrink = 0;
|
|
3415
|
+
|
|
3416
|
+
box.lblTitle = Label({ ..._s.title, ellipsis: 1, css: { maxWidth: "100%" } });
|
|
3417
|
+
// WHY no "...": A subtitle is a sentence that can explain the chart. On a phone it goes on the next line.
|
|
3418
|
+
box.lblSubtitle = Label({ ..._s.subtitle, css: { maxWidth: "100%", whiteSpace: "normal", textWrap: "balance" } });
|
|
3419
|
+
|
|
3420
|
+
endGroup();
|
|
3421
|
+
|
|
3422
|
+
// GROUP: The legend and the chart. (Their order comes from the place of the legend.)
|
|
3423
|
+
box.body = VGroup({ width: "100%", height: "auto", align: "left top", gap: _s.box.gap });
|
|
3424
|
+
box.body.css = { flex: "1 1 0", minHeight: "0px" };
|
|
3425
|
+
|
|
3426
|
+
box.legendGroup = HGroup({ width: "100%", height: "auto", align: "left center", wrap: 1 });
|
|
3427
|
+
box.legendGroup.shrink = 0;
|
|
3428
|
+
box.legendGroup.css = { rowGap: _s.legend.lineGap + "px", columnGap: _s.legend.gap + "px", maxWidth: "100%" };
|
|
3429
|
+
endGroup();
|
|
3430
|
+
|
|
3431
|
+
// BOX: The plot. (The SVG is out of the flow: its size must not hold the box open when the box gets smaller.)
|
|
3432
|
+
box.plot = startBox({ width: "100%", height: "auto", color: "transparent" });
|
|
3433
|
+
box.plot.css = { flex: "1 1 0", minWidth: "0px", minHeight: "0px", alignSelf: "stretch", touchAction: "pan-y" };
|
|
3434
|
+
|
|
3435
|
+
// LABEL: No values
|
|
3436
|
+
box.lblEmpty = Label({ left: 0, width: "100%", textAlign: "center", fontSize: _s.axis.fontSize, visible: 0 });
|
|
3437
|
+
box.lblEmpty.css = { top: "calc(50% - 10px)" };
|
|
3438
|
+
|
|
3439
|
+
endBox();
|
|
3440
|
+
|
|
3441
|
+
endGroup();
|
|
3442
|
+
|
|
3443
|
+
endGroup();
|
|
3444
|
+
|
|
3445
|
+
// SVG: The chart
|
|
3446
|
+
svg = createSvgElement("svg", { "aria-hidden": "true" });
|
|
3447
|
+
box.svg = svg;
|
|
3448
|
+
svg.style.cssText = "position: absolute; left: 0; top: 0; display: block;";
|
|
3449
|
+
definitions = addShape(svg, "defs", {});
|
|
3450
|
+
gridLayer = addShape(svg, "g", {});
|
|
3451
|
+
washLayer = addShape(svg, "g", {}); // The band under the mouse: behind the marks
|
|
3452
|
+
clipLayer = addShape(svg, "g", {}); // WHY two: A live chart moves markLayer, and its clip must stay where it is.
|
|
3453
|
+
markLayer = addShape(clipLayer, "g", {});
|
|
3454
|
+
overlayLayer = addShape(svg, "g", {}); // The points under the mouse: over the marks
|
|
3455
|
+
valueLayer = addShape(svg, "g", {}); // The texts of the values: not clipped with the marks
|
|
3456
|
+
box.plot.elem.appendChild(svg);
|
|
3457
|
+
|
|
3458
|
+
// GROUP: Tooltip (out of the layout, it never catches the mouse)
|
|
3459
|
+
box.tooltip = VGroup({
|
|
3460
|
+
left: 0,
|
|
3461
|
+
top: 0,
|
|
3462
|
+
hug: 1,
|
|
3463
|
+
align: "left top",
|
|
3464
|
+
gap: _s.tooltip.gap,
|
|
3465
|
+
padding: _s.tooltip.padding,
|
|
3466
|
+
round: _s.tooltip.round,
|
|
3467
|
+
});
|
|
3468
|
+
|
|
3469
|
+
box.lblTooltipTitle = Label({ fontSize: _s.tooltip.fontSize, ellipsis: 1 });
|
|
3470
|
+
|
|
3471
|
+
// NOTE: The rows are made by fillTooltip().
|
|
3472
|
+
|
|
3473
|
+
endGroup();
|
|
3474
|
+
box.tooltip.boxShadow = _s.tooltip.shadow;
|
|
3475
|
+
box.tooltip.zIndex = 1;
|
|
3476
|
+
box.tooltip.role = "status"; // WHY: A screen reader reads the value the arrow keys chose.
|
|
3477
|
+
box.tooltip.visible = 0;
|
|
3478
|
+
|
|
3479
|
+
// *** OBJECT INIT CODE:
|
|
3480
|
+
|
|
3481
|
+
box.data = createData();
|
|
3482
|
+
|
|
3483
|
+
box.plot.role = "img";
|
|
3484
|
+
box.plot.tabIndex = 0;
|
|
3485
|
+
box.plot.on("pointermove", onPlotPointerMove);
|
|
3486
|
+
box.plot.on("pointerdown", onPlotPointerMove);
|
|
3487
|
+
box.plot.on("pointerleave", onPlotPointerLeave);
|
|
3488
|
+
box.plot.on("click", function (self, event) { runClickEvent(event); });
|
|
3489
|
+
box.plot.on("keydown", onPlotKeyDown);
|
|
3490
|
+
box.plot.on("focus", onPlotFocus);
|
|
3491
|
+
box.plot.on("blur", clearActiveItem);
|
|
3492
|
+
box.plot.onResize(onPlotResize);
|
|
3493
|
+
box.listenTo(document, "pointerdown", onDocumentPointerDown);
|
|
3494
|
+
|
|
3495
|
+
if (window.matchMedia) {
|
|
3496
|
+
box.listenTo(window.matchMedia("(prefers-color-scheme: dark)"), "change", onSystemThemeChange);
|
|
3497
|
+
}
|
|
3498
|
+
|
|
3499
|
+
drawAll();
|
|
3500
|
+
redrawWhenFontIsLoaded();
|
|
3501
|
+
|
|
3502
|
+
return endObject(box);
|
|
3503
|
+
|
|
3504
|
+
};
|
|
3505
|
+
|
|
3506
|
+
// *** STATIC VARIABLES:
|
|
3507
|
+
|
|
3508
|
+
GraphBox._idCounter = 0; // WHY: The id of a gradient or a clip must be alone on the whole page.
|
|
3509
|
+
GraphBox.OTHER_SLICE = -1; // The index of the "Other" slice of a pie
|
|
3510
|
+
|
|
3511
|
+
// *** THEMES: the colors. (The style param has the shapes; style.colors changes some colors of one chart.)
|
|
3512
|
+
// USAGE: GraphBox({ theme: "dark", ... }) // "light", "dark", "auto" (the system setting)
|
|
3513
|
+
// NOTE: A new theme needs only the keys that differ from the light theme.
|
|
3514
|
+
// USAGE: GraphBox.THEMES.ocean = { backgroundColor: "#0B2239", textColor: "#C9D6E3" };
|
|
3515
|
+
// NOTE: The order of the colors is not free: it was checked for color blindness. (First 3 are the safest.)
|
|
3516
|
+
GraphBox.THEMES = {
|
|
3517
|
+
light: {
|
|
3518
|
+
backgroundColor: "#FCFCFB",
|
|
3519
|
+
borderColor: "rgba(11, 11, 11, 0.10)",
|
|
3520
|
+
titleColor: "#0B0B0B",
|
|
3521
|
+
textColor: "#52514E",
|
|
3522
|
+
mutedTextColor: "#898781",
|
|
3523
|
+
gridColor: "#E1E0D9",
|
|
3524
|
+
axisColor: "#C3C2B7",
|
|
3525
|
+
hoverColor: "rgba(11, 11, 11, 0.05)",
|
|
3526
|
+
targetColor: "#52514E",
|
|
3527
|
+
focusColor: "rgba(42, 120, 214, 0.7)",
|
|
3528
|
+
otherColor: "#A9A8A0",
|
|
3529
|
+
tooltipColor: "#0B0B0B",
|
|
3530
|
+
tooltipTextColor: "#FFFFFF",
|
|
3531
|
+
tooltipMutedColor: "rgba(255, 255, 255, 0.65)",
|
|
3532
|
+
colors: ["#2A78D6", "#EB6834", "#1BAF7A", "#EDA100", "#E87BA4", "#008300", "#6250D6", "#E34948"],
|
|
3533
|
+
},
|
|
3534
|
+
dark: {
|
|
3535
|
+
backgroundColor: "#1A1A19",
|
|
3536
|
+
borderColor: "rgba(255, 255, 255, 0.10)",
|
|
3537
|
+
titleColor: "#F0EFEC",
|
|
3538
|
+
textColor: "#C3C2B7",
|
|
3539
|
+
mutedTextColor: "#898781",
|
|
3540
|
+
gridColor: "#2C2C2A",
|
|
3541
|
+
axisColor: "#383835",
|
|
3542
|
+
hoverColor: "rgba(255, 255, 255, 0.06)",
|
|
3543
|
+
targetColor: "#C3C2B7",
|
|
3544
|
+
focusColor: "rgba(57, 135, 229, 0.8)",
|
|
3545
|
+
otherColor: "#6F6E69",
|
|
3546
|
+
tooltipColor: "#2C2C2A",
|
|
3547
|
+
tooltipTextColor: "#FFFFFF",
|
|
3548
|
+
tooltipMutedColor: "rgba(255, 255, 255, 0.65)",
|
|
3549
|
+
colors: ["#3987E5", "#D95926", "#199E70", "#C98500", "#D55181", "#008300", "#9085E9", "#E66767"],
|
|
3550
|
+
},
|
|
3551
|
+
};
|
|
3552
|
+
|
|
3553
|
+
// The minimal theme (_designs/minimal-theme.htm): the ground of the window with a soft line, the text tokens of the
|
|
3554
|
+
// theme, a faint grid. style: its shapes too (a theme with a style gives the shapes, under the style of the page):
|
|
3555
|
+
// 13 px title, 11 px axis and legend, round 4, thin lines, a tooltip with no shadow.
|
|
3556
|
+
// WHY the colors of the data are those of light / dark: they were checked for color blindness.
|
|
3557
|
+
GraphBox.MINIMAL_SHAPES = {
|
|
3558
|
+
box: { round: 4, padding: 12, gap: 10 },
|
|
3559
|
+
title: { fontSize: 13, fontFamily: "opensans-bold" },
|
|
3560
|
+
subtitle: { fontSize: 11 },
|
|
3561
|
+
legend: {
|
|
3562
|
+
keys: {
|
|
3563
|
+
line: { width: 12, height: 2, round: 1 },
|
|
3564
|
+
box: { width: 8, height: 8, round: 2 },
|
|
3565
|
+
dot: { width: 6, height: 6, round: 3 },
|
|
3566
|
+
},
|
|
3567
|
+
fontSize: 11,
|
|
3568
|
+
gap: 12,
|
|
3569
|
+
lineGap: 4,
|
|
3570
|
+
keyGap: 5,
|
|
3571
|
+
},
|
|
3572
|
+
axis: { fontSize: 11 },
|
|
3573
|
+
bar: { maxThickness: 20, round: 2 },
|
|
3574
|
+
line: { width: 1.5, pointRadius: 3, pointRing: 1.5 },
|
|
3575
|
+
pie: { centerFontSize: 20 },
|
|
3576
|
+
table: { fontSize: 11, rowHeight: 24 },
|
|
3577
|
+
tooltip: { fontSize: 11, round: 4, padding: [8, 6], shadow: "none" },
|
|
3578
|
+
};
|
|
3579
|
+
GraphBox.THEMES.minimal = {
|
|
3580
|
+
backgroundColor: "#FFFFFF",
|
|
3581
|
+
borderColor: Black(0.2),
|
|
3582
|
+
titleColor: Black(0.85),
|
|
3583
|
+
textColor: Black(0.55),
|
|
3584
|
+
mutedTextColor: Black(0.54),
|
|
3585
|
+
gridColor: Black(0.08),
|
|
3586
|
+
axisColor: Black(0.2),
|
|
3587
|
+
hoverColor: Black(0.04),
|
|
3588
|
+
targetColor: Black(0.55),
|
|
3589
|
+
focusColor: "#3D8BD9",
|
|
3590
|
+
otherColor: Black(0.3),
|
|
3591
|
+
tooltipColor: "#1F1F1F",
|
|
3592
|
+
tooltipTextColor: "#FFFFFF",
|
|
3593
|
+
tooltipMutedColor: White(0.65),
|
|
3594
|
+
colors: GraphBox.THEMES.light.colors,
|
|
3595
|
+
style: GraphBox.MINIMAL_SHAPES,
|
|
3596
|
+
};
|
|
3597
|
+
GraphBox.THEMES.minimalDark = {
|
|
3598
|
+
backgroundColor: "#1A1A19",
|
|
3599
|
+
borderColor: White(0.18),
|
|
3600
|
+
titleColor: White(0.88),
|
|
3601
|
+
textColor: White(0.55),
|
|
3602
|
+
mutedTextColor: White(0.48),
|
|
3603
|
+
gridColor: White(0.07),
|
|
3604
|
+
axisColor: White(0.18),
|
|
3605
|
+
hoverColor: White(0.05),
|
|
3606
|
+
targetColor: White(0.55),
|
|
3607
|
+
focusColor: "#7FB6DE",
|
|
3608
|
+
otherColor: White(0.3),
|
|
3609
|
+
tooltipColor: "#EDEDEB",
|
|
3610
|
+
tooltipTextColor: "#1A1A19",
|
|
3611
|
+
tooltipMutedColor: Black(0.6),
|
|
3612
|
+
colors: GraphBox.THEMES.dark.colors,
|
|
3613
|
+
style: GraphBox.MINIMAL_SHAPES,
|
|
3614
|
+
};
|
|
3615
|
+
|
|
3616
|
+
// *** STATIC FUNCTIONS: the math of a chart. They need no box.
|
|
3617
|
+
|
|
3618
|
+
// The clean step of an axis: { step, decimals }. tickCount: about how many spaces between the ticks.
|
|
3619
|
+
GraphBox.findNiceStep = function (low, high, tickCount) {
|
|
3620
|
+
|
|
3621
|
+
// WHY the tolerance: A rough step of 1.08 would become 2, and half of the chart would be empty. A step a little
|
|
3622
|
+
// under the rough one only adds a line or two.
|
|
3623
|
+
const STEP_TOLERANCE = 1.2;
|
|
3624
|
+
const roughStep = (high - low) / Math.max(1, tickCount);
|
|
3625
|
+
const power = Math.pow(10, Math.floor(Math.log10(roughStep)));
|
|
3626
|
+
const fraction = [1, 2, 2.5, 5, 10].find(function (candidate) {
|
|
3627
|
+
return (roughStep / power <= candidate * STEP_TOLERANCE);
|
|
3628
|
+
});
|
|
3629
|
+
|
|
3630
|
+
return {
|
|
3631
|
+
step: fraction * power,
|
|
3632
|
+
decimals: Math.max(0, -Math.floor(Math.log10(power))) + ((fraction === 2.5) ? 1 : 0),
|
|
3633
|
+
};
|
|
3634
|
+
|
|
3635
|
+
};
|
|
3636
|
+
|
|
3637
|
+
// How many digits a number has after its point. 0.25 -> 2
|
|
3638
|
+
GraphBox.countDecimals = function (number) {
|
|
3639
|
+
const parts = String(number).split(".");
|
|
3640
|
+
return (parts[1]) ? parts[1].length : 0;
|
|
3641
|
+
};
|
|
3642
|
+
|
|
3643
|
+
// Clean numbers for an axis: { min, max, ticks, decimals }. tickCount: about how many spaces between the ticks.
|
|
3644
|
+
// fixedStep: the step of the page. (Ex: 1: every floor of a building.)
|
|
3645
|
+
GraphBox.niceScale = function (low, high, tickCount = 5, fixedStep = 0) {
|
|
3646
|
+
|
|
3647
|
+
if (!(high > low)) {
|
|
3648
|
+
// WHY: One value (or all the same): the scale needs some height, or every place divides by 0.
|
|
3649
|
+
const room = Math.abs(low) * 0.1 || 1;
|
|
3650
|
+
low = (low === 0) ? 0 : low - room;
|
|
3651
|
+
high = high + room;
|
|
3652
|
+
}
|
|
3653
|
+
|
|
3654
|
+
// WHY the limit: A small step on a very wide axis would make millions of lines and freeze the page.
|
|
3655
|
+
const MAX_FIXED_TICKS = 500;
|
|
3656
|
+
const canUseFixedStep = (fixedStep > 0 && (high - low) / fixedStep <= MAX_FIXED_TICKS);
|
|
3657
|
+
const found = (canUseFixedStep)
|
|
3658
|
+
? { step: fixedStep, decimals: GraphBox.countDecimals(fixedStep) }
|
|
3659
|
+
: GraphBox.findNiceStep(low, high, tickCount);
|
|
3660
|
+
const step = found.step;
|
|
3661
|
+
|
|
3662
|
+
// WHY the small number: 0.3 / 0.1 is 2.9999999999999996, and its floor would add a tick under the values.
|
|
3663
|
+
const CALCULATION_ERROR = 1e-9;
|
|
3664
|
+
const firstPlace = Math.floor(low / step + CALCULATION_ERROR);
|
|
3665
|
+
const lastPlace = Math.ceil(high / step - CALCULATION_ERROR);
|
|
3666
|
+
|
|
3667
|
+
const ticks = [];
|
|
3668
|
+
for (let place = firstPlace; place <= lastPlace; place++) {
|
|
3669
|
+
ticks.push(Number((place * step).toFixed(found.decimals)));
|
|
3670
|
+
}
|
|
3671
|
+
|
|
3672
|
+
return { min: ticks[0], max: ticks[ticks.length - 1], ticks: ticks, decimals: found.decimals };
|
|
3673
|
+
|
|
3674
|
+
};
|
|
3675
|
+
|
|
3676
|
+
// 42000 -> "42,000" (in the language of the browser, or locale)
|
|
3677
|
+
GraphBox.formatNumber = function (value, locale) {
|
|
3678
|
+
return value.toLocaleString(locale || undefined, { maximumFractionDigits: 6 });
|
|
3679
|
+
};
|
|
3680
|
+
|
|
3681
|
+
// 42000 -> "42K" (A text of an axis: short)
|
|
3682
|
+
GraphBox.formatCompactNumber = function (value, locale, decimals = 0) {
|
|
3683
|
+
const options = { notation: "compact", maximumFractionDigits: Math.max(2, decimals) };
|
|
3684
|
+
return value.toLocaleString(locale || undefined, options);
|
|
3685
|
+
};
|
|
3686
|
+
|
|
3687
|
+
// 0.423 -> "42.3%"
|
|
3688
|
+
GraphBox.formatPercent = function (share, locale) {
|
|
3689
|
+
return share.toLocaleString(locale || undefined, { style: "percent", maximumFractionDigits: 1 });
|
|
3690
|
+
};
|
|
3691
|
+
|
|
3692
|
+
GraphBox.measureText = function (text, fontSize, fontFamily) {
|
|
3693
|
+
if (!GraphBox._measureContext) GraphBox._measureContext = document.createElement("canvas").getContext("2d");
|
|
3694
|
+
GraphBox._measureContext.font = fontSize + "px " + fontFamily;
|
|
3695
|
+
return GraphBox._measureContext.measureText(String(text)).width;
|
|
3696
|
+
};
|
|
3697
|
+
|
|
3698
|
+
// The text, cut with "..." when it is wider than maxWidth.
|
|
3699
|
+
GraphBox.fitText = function (text, maxWidth, fontSize, fontFamily) {
|
|
3700
|
+
const isFitting = function (candidate) {
|
|
3701
|
+
return (GraphBox.measureText(candidate, fontSize, fontFamily) <= maxWidth);
|
|
3702
|
+
};
|
|
3703
|
+
if (isFitting(text)) return text;
|
|
3704
|
+
let length = text.length - 1;
|
|
3705
|
+
while (length > 0 && !isFitting(text.slice(0, length) + "…")) length--;
|
|
3706
|
+
return text.slice(0, length) + "…";
|
|
3707
|
+
};
|
|
3708
|
+
|
|
3709
|
+
// The lines of a text in this width, with the font of the context. (The canvas does not wrap a text by itself.)
|
|
3710
|
+
// WHY the small room: A text that just fits its label is not wrapped for a part of a px of a measure.
|
|
3711
|
+
GraphBox.wrapText = function (context, text, maxWidth) {
|
|
3712
|
+
const MEASURE_ROOM = 1;
|
|
3713
|
+
const lines = [];
|
|
3714
|
+
let line = "";
|
|
3715
|
+
text.split(" ").forEach(function (word) {
|
|
3716
|
+
const longerLine = (line) ? line + " " + word : word;
|
|
3717
|
+
if (line && context.measureText(longerLine).width > maxWidth + MEASURE_ROOM) {
|
|
3718
|
+
lines.push(line);
|
|
3719
|
+
line = word;
|
|
3720
|
+
return;
|
|
3721
|
+
}
|
|
3722
|
+
line = longerLine;
|
|
3723
|
+
});
|
|
3724
|
+
lines.push(line);
|
|
3725
|
+
return lines;
|
|
3726
|
+
};
|
|
3727
|
+
|
|
3728
|
+
GraphBox.pointText = function (point) {
|
|
3729
|
+
return GraphBox.roundNumber(point.x) + " " + GraphBox.roundNumber(point.y) + " ";
|
|
3730
|
+
};
|
|
3731
|
+
|
|
3732
|
+
// WHY: A long number in every path only makes the page bigger; a hundredth of a px can not be seen.
|
|
3733
|
+
GraphBox.roundNumber = function (value) {
|
|
3734
|
+
return Math.round(value * 100) / 100;
|
|
3735
|
+
};
|
|
3736
|
+
|
|
3737
|
+
// A rectangle with round corners only at one side (the end of the value). side: "top", "bottom", "left", "right", ""
|
|
3738
|
+
GraphBox.barPath = function (rect, round, side) {
|
|
3739
|
+
|
|
3740
|
+
const left = rect.left;
|
|
3741
|
+
const right = rect.left + rect.width;
|
|
3742
|
+
const top = rect.top;
|
|
3743
|
+
const bottom = rect.top + rect.height;
|
|
3744
|
+
const isUpright = (side === "top" || side === "bottom");
|
|
3745
|
+
const radius = (isUpright) ? Math.min(round, rect.width / 2, rect.height) : Math.min(round, rect.height / 2, rect.width);
|
|
3746
|
+
|
|
3747
|
+
const topLeft = (side === "top" || side === "left") ? radius : 0;
|
|
3748
|
+
const topRight = (side === "top" || side === "right") ? radius : 0;
|
|
3749
|
+
const bottomRight = (side === "bottom" || side === "right") ? radius : 0;
|
|
3750
|
+
const bottomLeft = (side === "bottom" || side === "left") ? radius : 0;
|
|
3751
|
+
|
|
3752
|
+
const point = function (x, y) { return GraphBox.pointText({ x: x, y: y }); };
|
|
3753
|
+
|
|
3754
|
+
return "M" + point(left + topLeft, top) +
|
|
3755
|
+
"L" + point(right - topRight, top) + "Q" + point(right, top) + point(right, top + topRight) +
|
|
3756
|
+
"L" + point(right, bottom - bottomRight) + "Q" + point(right, bottom) + point(right - bottomRight, bottom) +
|
|
3757
|
+
"L" + point(left + bottomLeft, bottom) + "Q" + point(left, bottom) + point(left, bottom - bottomLeft) +
|
|
3758
|
+
"L" + point(left, top + topLeft) + "Q" + point(left, top) + point(left + topLeft, top) + "Z";
|
|
3759
|
+
|
|
3760
|
+
};
|
|
3761
|
+
|
|
3762
|
+
// Can the browser move the "d" of a path with a transition?
|
|
3763
|
+
GraphBox.canMovePaths = function () {
|
|
3764
|
+
return !!(window.CSS && CSS.supports && CSS.supports("d", 'path("M0 0")'));
|
|
3765
|
+
};
|
|
3766
|
+
|
|
3767
|
+
// The red, green, blue and alpha of any color the browser knows. WHY the canvas: It reads every way to write a color.
|
|
3768
|
+
GraphBox.readColor = function (color) {
|
|
3769
|
+
if (!GraphBox._colorContext) {
|
|
3770
|
+
const canvas = document.createElement("canvas");
|
|
3771
|
+
canvas.width = 1;
|
|
3772
|
+
canvas.height = 1;
|
|
3773
|
+
GraphBox._colorContext = canvas.getContext("2d", { willReadFrequently: true });
|
|
3774
|
+
}
|
|
3775
|
+
const context = GraphBox._colorContext;
|
|
3776
|
+
context.clearRect(0, 0, 1, 1);
|
|
3777
|
+
context.fillStyle = color;
|
|
3778
|
+
context.fillRect(0, 0, 1, 1);
|
|
3779
|
+
return context.getImageData(0, 0, 1, 1).data;
|
|
3780
|
+
};
|
|
3781
|
+
|
|
3782
|
+
// "#2A78D6", 0.3 -> "rgba(42, 120, 214, 0.3)"
|
|
3783
|
+
GraphBox.toTransparent = function (color, opacity) {
|
|
3784
|
+
const rgba = GraphBox.readColor(color);
|
|
3785
|
+
return "rgba(" + rgba[0] + ", " + rgba[1] + ", " + rgba[2] + ", " + opacity + ")";
|
|
3786
|
+
};
|
|
3787
|
+
|
|
3788
|
+
// White or ink for a text on this color. WHY not the color of the data: A text must be read.
|
|
3789
|
+
GraphBox.getTextColorOn = function (color) {
|
|
3790
|
+
const rgba = GraphBox.readColor(color);
|
|
3791
|
+
const toLinear = function (part) {
|
|
3792
|
+
const share = part / 255;
|
|
3793
|
+
return (share <= 0.03928) ? share / 12.92 : Math.pow((share + 0.055) / 1.055, 2.4);
|
|
3794
|
+
};
|
|
3795
|
+
const luminance = 0.2126 * toLinear(rgba[0]) + 0.7152 * toLinear(rgba[1]) + 0.0722 * toLinear(rgba[2]);
|
|
3796
|
+
const DARK_TEXT_LUMINANCE = 0.2; // From here the ink is easier to read than white.
|
|
3797
|
+
return (luminance > DARK_TEXT_LUMINANCE) ? "#0B0B0B" : "#FFFFFF";
|
|
3798
|
+
};
|
|
3799
|
+
|
|
3800
|
+
// A closed shape through the points.
|
|
3801
|
+
GraphBox.polygonPath = function (points) {
|
|
3802
|
+
if (!points.length) return "";
|
|
3803
|
+
return "M" + points.map(function (point) { return GraphBox.pointText(point); }).join("L") + "Z";
|
|
3804
|
+
};
|
|
3805
|
+
|
|
3806
|
+
// A whole circle or ring. WHY two arcs: One arc from a point to the same point draws nothing.
|
|
3807
|
+
GraphBox.ringPath = function (center, innerRadius, outerRadius) {
|
|
3808
|
+
const circle = function (radius, direction) {
|
|
3809
|
+
const first = GraphBox.pointText({ x: center.x - radius, y: center.y });
|
|
3810
|
+
const second = GraphBox.pointText({ x: center.x + radius, y: center.y });
|
|
3811
|
+
const arc = "A" + radius + " " + radius + " 0 1 " + direction + " ";
|
|
3812
|
+
return "M" + first + arc + second + arc + first + "Z";
|
|
3813
|
+
};
|
|
3814
|
+
// WHY the other direction: A path that turns the other way makes a hole.
|
|
3815
|
+
return circle(outerRadius, 1) + ((innerRadius > 0) ? circle(innerRadius, 0) : "");
|
|
3816
|
+
};
|
|
3817
|
+
|
|
3818
|
+
// A slice of a pie or a ring. Angles in radians, growing clockwise.
|
|
3819
|
+
// WHY the gap is in the geometry: A line in the color of the box would not be seen on a box with no color. Half of the
|
|
3820
|
+
// gap is the same px at every radius, so the sides of a slice stay parallel to the sides of the next one.
|
|
3821
|
+
GraphBox.slicePath = function (center, innerRadius, outerRadius, startAngle, endAngle, gap) {
|
|
3822
|
+
|
|
3823
|
+
const sweep = endAngle - startAngle;
|
|
3824
|
+
if (sweep >= Math.PI * 2 - 0.0001) return GraphBox.ringPath(center, innerRadius, outerRadius);
|
|
3825
|
+
|
|
3826
|
+
const pointAt = function (radius, angle) {
|
|
3827
|
+
return GraphBox.pointText({ x: center.x + radius * Math.cos(angle), y: center.y + radius * Math.sin(angle) });
|
|
3828
|
+
};
|
|
3829
|
+
const arcTo = function (radius, angle, isLarge, direction) {
|
|
3830
|
+
return "A" + radius + " " + radius + " 0 " + (isLarge ? 1 : 0) + " " + direction + " " + pointAt(radius, angle);
|
|
3831
|
+
};
|
|
3832
|
+
|
|
3833
|
+
// A slice thinner than the gap keeps no gap: it must still be seen.
|
|
3834
|
+
const halfGap = (sweep > gap / outerRadius) ? gap / 2 : 0;
|
|
3835
|
+
const outerPad = halfGap / outerRadius;
|
|
3836
|
+
const innerPad = (innerRadius > 0) ? halfGap / innerRadius : Infinity;
|
|
3837
|
+
|
|
3838
|
+
const outerSweep = sweep - outerPad * 2;
|
|
3839
|
+
let path = "M" + pointAt(outerRadius, startAngle + outerPad) + arcTo(outerRadius, endAngle - outerPad, outerSweep > Math.PI, 1);
|
|
3840
|
+
|
|
3841
|
+
if (sweep > innerPad * 2) {
|
|
3842
|
+
const innerSweep = sweep - innerPad * 2;
|
|
3843
|
+
path += "L" + pointAt(innerRadius, endAngle - innerPad) + arcTo(innerRadius, startAngle + innerPad, innerSweep > Math.PI, 0);
|
|
3844
|
+
return path + "Z";
|
|
3845
|
+
}
|
|
3846
|
+
|
|
3847
|
+
// The two sides meet before the hole, on the middle line of the slice.
|
|
3848
|
+
// WHY the limit: The sides of a very big slice meet far away; near the center nobody can see the small difference.
|
|
3849
|
+
const meetDistance = halfGap / Math.sin(sweep / 2);
|
|
3850
|
+
const meetRadius = (sweep > Math.PI) ? Math.min(meetDistance, gap) : meetDistance;
|
|
3851
|
+
path += "L" + pointAt(Math.max(innerRadius, meetRadius), startAngle + sweep / 2);
|
|
3852
|
+
return path + "Z";
|
|
3853
|
+
|
|
3854
|
+
};
|
|
3855
|
+
|
|
3856
|
+
// The commands of a line that starts at the first point (its "M" is written by the caller).
|
|
3857
|
+
GraphBox.curveCommands = function (points, isSmooth, isHorizontal) {
|
|
3858
|
+
|
|
3859
|
+
if (isSmooth && points.length > 2) return GraphBox.smoothCommands(points, isHorizontal);
|
|
3860
|
+
|
|
3861
|
+
let commands = "";
|
|
3862
|
+
for (let i = 1; i < points.length; i++) commands += "L" + GraphBox.pointText(points[i]);
|
|
3863
|
+
return commands;
|
|
3864
|
+
|
|
3865
|
+
};
|
|
3866
|
+
|
|
3867
|
+
// A smooth line that never goes over or under a value (monotone cubic).
|
|
3868
|
+
// WHY monotone: A plain curve makes a hill higher than the real value; a chart must not show a value that is not there.
|
|
3869
|
+
// NOTE: The line moves forward on the index axis: on x, or on y on a horizontal chart.
|
|
3870
|
+
GraphBox.smoothCommands = function (points, isHorizontal) {
|
|
3871
|
+
|
|
3872
|
+
const indexKey = (isHorizontal) ? "y" : "x";
|
|
3873
|
+
const valueKey = (isHorizontal) ? "x" : "y";
|
|
3874
|
+
const count = points.length;
|
|
3875
|
+
const widths = [];
|
|
3876
|
+
const slopes = [];
|
|
3877
|
+
|
|
3878
|
+
for (let i = 0; i < count - 1; i++) {
|
|
3879
|
+
widths[i] = points[i + 1][indexKey] - points[i][indexKey];
|
|
3880
|
+
slopes[i] = (points[i + 1][valueKey] - points[i][valueKey]) / widths[i];
|
|
3881
|
+
}
|
|
3882
|
+
|
|
3883
|
+
const tangents = [slopes[0]];
|
|
3884
|
+
for (let i = 1; i < count - 1; i++) {
|
|
3885
|
+
if (slopes[i - 1] * slopes[i] <= 0) {
|
|
3886
|
+
tangents[i] = 0; // A hill or a valley: the curve is flat at its value.
|
|
3887
|
+
continue;
|
|
3888
|
+
}
|
|
3889
|
+
const firstWeight = 2 * widths[i] + widths[i - 1];
|
|
3890
|
+
const secondWeight = widths[i] + 2 * widths[i - 1];
|
|
3891
|
+
tangents[i] = (firstWeight + secondWeight) / (firstWeight / slopes[i - 1] + secondWeight / slopes[i]);
|
|
3892
|
+
}
|
|
3893
|
+
tangents[count - 1] = slopes[count - 2];
|
|
3894
|
+
|
|
3895
|
+
const createControl = function (indexPosition, valuePosition) {
|
|
3896
|
+
const control = {};
|
|
3897
|
+
control[indexKey] = indexPosition;
|
|
3898
|
+
control[valueKey] = valuePosition;
|
|
3899
|
+
return control;
|
|
3900
|
+
};
|
|
3901
|
+
|
|
3902
|
+
let commands = "";
|
|
3903
|
+
for (let i = 0; i < count - 1; i++) {
|
|
3904
|
+
const third = widths[i] / 3;
|
|
3905
|
+
const firstControl = createControl(points[i][indexKey] + third, points[i][valueKey] + tangents[i] * third);
|
|
3906
|
+
const secondControl = createControl(points[i + 1][indexKey] - third, points[i + 1][valueKey] - tangents[i + 1] * third);
|
|
3907
|
+
commands += "C" + GraphBox.pointText(firstControl) + GraphBox.pointText(secondControl) + GraphBox.pointText(points[i + 1]);
|
|
3908
|
+
}
|
|
3909
|
+
return commands;
|
|
3910
|
+
|
|
3911
|
+
};
|