@vixoniccom/kpi-chart 0.0.1-beta.1

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.
@@ -0,0 +1,182 @@
1
+ import axios from "axios";
2
+ import localforage from "localforage";
3
+ import React, { useState, useEffect } from "react";
4
+ import { FontLoader } from "./FontLoader";
5
+ import { ChartContainer } from "./ChartContainer";
6
+ import { FormattedText } from "./FormattedText";
7
+ import "../style.css";
8
+ import {
9
+ checkDataHealth,
10
+ dataToSeries,
11
+ getCleanData,
12
+ nameInHeaders,
13
+ sliceFeatures,
14
+ sliceRecords,
15
+ } from "./utils";
16
+
17
+ interface Props {
18
+ data: VixonicData;
19
+ start: boolean;
20
+ }
21
+
22
+ // Definición de paths de las fuentes provenientes de la configuración
23
+ const fontPaths = [
24
+ "titleTextFormat.font",
25
+ "legendTextFormat.font",
26
+ "customMessageTextFormat.font",
27
+ ];
28
+
29
+ /**
30
+ * Componente principal que muestra la aplicación y el gráfico.
31
+ * Es llamada una vez ha sido inicializada (start == true).
32
+ * Obtiene los datos según tiempo de actualización definido en la configuración.
33
+ */
34
+ export const App: React.FunctionComponent<Props> = ({ data, start }) => {
35
+ let updateTimer: any;
36
+ const params = data.parameters;
37
+ const appPadding = params?.appPadding || "0px";
38
+ const updateTime = params?.updateTime || 3600000;
39
+ const backgroundImageState = params?.backgroundImage
40
+ ? `url("${data.downloadsPath}/${params?.backgroundImage.filename}")`
41
+ : "";
42
+ // Definición de variable que contiene los datos procesados provenientes de la URL
43
+ const [sheetData, setSheetData] = useState<Series[]>([]);
44
+ // Definición de mensaje del sistema
45
+ const [systemMessage, setSystemMessage] = useState<string>(
46
+ "Sin datos disponibles"
47
+ );
48
+ // Definición de nombre fijo de columna de categoría
49
+ const categoryColumnName = "categoria";
50
+ // Definición de cantidad máxima de columnas y filas para procesar desde Google
51
+ const fixedMaxRows = 100;
52
+ const fixedMaxColumns = 10; // 10 máx, no usar más, a menos que sea agreguen más colores en ChartContainer
53
+ // Definición de cantidad de columnas y filas para mostrar en la aplicación
54
+ const rowsNumber = params?.maxRowsNumber || 6;
55
+ const columnsNumber = params?.maxColumnsNumber || 3;
56
+
57
+ // Función para hacer request de Google y almacenar los datos procesados en localforage
58
+ const getData = async () => {
59
+ const googleID = params?.url?.split("/")[5];
60
+ const key = getStorageKey(googleID);
61
+ const storedData: any = await localforage.getItem(key);
62
+ if (!storedData?.items || storedData?.items?.length === 0) {
63
+ const data = await requestData(googleID);
64
+ localforage.setItem(key, { items: data, date: Date.now() });
65
+ setDataAndTime(data, updateTime);
66
+ } else {
67
+ const now = Date.now();
68
+ const targetDate = storedData.date + updateTime;
69
+ if (now >= targetDate) {
70
+ const data = await requestData(googleID);
71
+ setDataAndTime(data, targetDate - now);
72
+ localforage.setItem(key, { items: data, date: now });
73
+ } else {
74
+ setDataAndTime(storedData.items, targetDate - now);
75
+ }
76
+ }
77
+ };
78
+
79
+ // Función para actualizar el estado de los datos y el tiempo de actualización
80
+ const setDataAndTime = (data: Series[], time: number) => {
81
+ setSheetData(
82
+ // Slice de columnas
83
+ sliceFeatures(
84
+ columnsNumber,
85
+ // Slice de filas
86
+ sliceRecords(rowsNumber, data)
87
+ )
88
+ );
89
+ setUpdateTime(time);
90
+ };
91
+
92
+ const setUpdateTime = (milliseconds: number) => {
93
+ clearTimeout(updateTimer);
94
+ if (milliseconds === null) return;
95
+ updateTimer = setTimeout(getData, milliseconds);
96
+ };
97
+
98
+ const requestData = async (googleID?: string) => {
99
+ const URL = `https://sheets.googleapis.com/v4/spreadsheets/${googleID}/values`;
100
+ try {
101
+ const response = await axios.get(`${URL}/data`, {
102
+ params: { key: "AIzaSyDQcTlxfd5IyjbeSJooRtNt6OF04DLykqc" },
103
+ });
104
+ return processData(response.data.values);
105
+ } catch (error: unknown) {
106
+ if (error instanceof Error) {
107
+ setSystemMessage(error.message);
108
+ } else {
109
+ setSystemMessage("Error al cargar los datos");
110
+ }
111
+ return [];
112
+ }
113
+ };
114
+
115
+ // Función para procesar datos (slice de filas, revisar integridad de datos y
116
+ // limpiar los datos)
117
+ const processData = (data: string[][]) => {
118
+ const [rawHeaders, ...rawRows] = data;
119
+ const rows = rawRows.slice(-fixedMaxRows);
120
+ if (isDataHealthy(rawHeaders, rows)) {
121
+ const cleanedData = getCleanData(categoryColumnName, fixedMaxColumns, [
122
+ rawHeaders,
123
+ ...rows,
124
+ ]);
125
+ // Si hay datos limpios, convertirlos a un arreglo de Series
126
+ if (cleanedData.length !== 0) {
127
+ return dataToSeries(categoryColumnName, cleanedData);
128
+ }
129
+ setSystemMessage("Después de limpieza, no hay datos para mostrar");
130
+ }
131
+ return [];
132
+ };
133
+
134
+ // Función para verificar si existe la columna de categoría y revisar la integridad de datos
135
+ const isDataHealthy = (headers: string[], rows: string[][]) => {
136
+ if (!nameInHeaders(categoryColumnName, headers)) {
137
+ setSystemMessage(`Columna '${categoryColumnName}' no existente`);
138
+ return false;
139
+ }
140
+ if (!checkDataHealth(headers, rows)) {
141
+ setSystemMessage("Falta de registros o columna con datos");
142
+ return false;
143
+ }
144
+ return true;
145
+ };
146
+
147
+ const getStorageKey = (googleID?: string) => {
148
+ const key = googleID?.replace(/[^a-z0-9]/gi, "");
149
+ return `sheets${key?.toLowerCase()}`;
150
+ };
151
+
152
+ useEffect(() => {
153
+ if (!start) return;
154
+ getData();
155
+ }, [params.url, params.maxRowsNumber, params.maxColumnsNumber, start]);
156
+
157
+ return (
158
+ <div
159
+ className="app-container"
160
+ style={{
161
+ padding: appPadding,
162
+ backgroundImage: `${backgroundImageState}`,
163
+ }}
164
+ >
165
+ {/* Carga de fuentes de texto */}
166
+ <FontLoader
167
+ paths={fontPaths}
168
+ parameters={params}
169
+ downloadsPath={data.downloadsPath}
170
+ />
171
+ {/* Render de chart o mensaje del sistema/personalizado */}
172
+ {sheetData.length > 0 ? (
173
+ <ChartContainer data={sheetData} parameters={params} />
174
+ ) : (
175
+ <FormattedText
176
+ text={params?.customMessage || systemMessage}
177
+ format={params?.systemMessageTextFormat}
178
+ />
179
+ )}
180
+ </div>
181
+ );
182
+ };
@@ -0,0 +1,171 @@
1
+ import React from "react";
2
+ import { Chart, AxisOptions } from "react-charts";
3
+ import { FormattedText } from "../FormattedText";
4
+ import { ChartLegend } from "../ChartLegend";
5
+
6
+ type Props = {
7
+ data: Series[];
8
+ parameters: VixonicParameters;
9
+ };
10
+
11
+ type elementType = "area" | "line" | "bar" | "bubble";
12
+
13
+ // Definición de colores que se utilizarán en el gráfico y leyenda
14
+ const defaultColors = [
15
+ "#1F77B4", // Azul
16
+ "#FF7F0E", // Naranja
17
+ "#D62728", // Rojo
18
+ "#2CA02C", // Verde
19
+ "#9467BD", // Morado
20
+ "#17BECF", // Cian
21
+ "#8C564B", // Marrón
22
+ "#E377C2", // Rosa
23
+ "#BCBD22", // Amarillo oliva
24
+ "#7F7F7F", // Gris
25
+ ];
26
+
27
+ /**
28
+ * Componente para renderizar el gráfico, su título y su leyenda.
29
+ * Se definen ejes principal y secundario en Memo para evitar problemas
30
+ de renderización.
31
+ */
32
+ export const ChartContainer: React.FunctionComponent<Props> = ({
33
+ data,
34
+ parameters,
35
+ }) => {
36
+ const chartTitle = parameters?.title || "";
37
+ const legendGap = parameters?.legendMargin || 0;
38
+ const titleMargin = parameters?.titlePadding || "0px";
39
+ const legendPosition = parameters?.legendPosition || "left";
40
+ const chartElementType = (parameters?.chartType as elementType) || "bar";
41
+ const titleFontColor = !parameters?.titleTextFormat?.fontColor
42
+ ? parameters?.darkMode
43
+ ? "white"
44
+ : "black"
45
+ : parameters?.titleTextFormat?.fontColor;
46
+
47
+ // Definición eje x
48
+ const primaryAxis = React.useMemo(
49
+ (): AxisOptions<KeyIndicator> => ({
50
+ getValue: (datum: KeyIndicator) => datum.category,
51
+ // Tipo band para variables categóricas
52
+ scaleType: "band",
53
+ showGrid: parameters?.showVerticalGrid,
54
+ show: parameters?.xAxisEnabled,
55
+ // Para barras horizontales
56
+ position:
57
+ chartElementType === "bar"
58
+ ? parameters?.barOrientation === "horizontal"
59
+ ? "left"
60
+ : "bottom"
61
+ : "bottom",
62
+ }),
63
+ [
64
+ parameters.showVerticalGrid,
65
+ parameters.xAxisEnabled,
66
+ parameters.barOrientation,
67
+ ]
68
+ );
69
+
70
+ // Definición eje y
71
+ const secondaryAxes = React.useMemo(
72
+ (): AxisOptions<KeyIndicator>[] => [
73
+ {
74
+ getValue: (datum: KeyIndicator) => datum.performance,
75
+ // Se define tipo de gráfico según la configuración
76
+ elementType: chartElementType,
77
+ scaleType: "linear",
78
+ showGrid: parameters?.showHorizontalGrid,
79
+ // Muestra de valores en número decimal
80
+ formatters: {
81
+ scale: (value) => value.toFixed(1),
82
+ },
83
+ show: parameters?.yAxisEnabled,
84
+ // Para barras apiladas
85
+ stacked:
86
+ chartElementType === "bar"
87
+ ? parameters?.barStacked
88
+ ? true
89
+ : false
90
+ : false,
91
+ // Para barras horizontales
92
+ position:
93
+ chartElementType === "bar"
94
+ ? parameters?.barOrientation === "horizontal"
95
+ ? "bottom"
96
+ : "left"
97
+ : "left",
98
+ },
99
+ ],
100
+ [
101
+ parameters.darkMode,
102
+ parameters.chartType,
103
+ parameters.barStacked,
104
+ parameters.yAxisEnabled,
105
+ parameters.showHorizontalGrid,
106
+ parameters.barOrientation,
107
+ ]
108
+ );
109
+
110
+ return (
111
+ <div className="chart-container">
112
+ {parameters?.titleEnabled && (
113
+ // Renderización del título del gráfico
114
+ <div
115
+ className="title-container"
116
+ style={{
117
+ padding: titleMargin,
118
+ }}
119
+ >
120
+ <FormattedText
121
+ text={chartTitle}
122
+ format={{
123
+ ...parameters?.titleTextFormat,
124
+ ...{ fontColor: titleFontColor },
125
+ }}
126
+ />
127
+ </div>
128
+ )}
129
+ {/* Renderización de leyenda y gráfico */}
130
+ <div
131
+ className="chart-elements"
132
+ style={{
133
+ flexDirection: legendPosition === "left" ? "row" : "row-reverse",
134
+ }}
135
+ >
136
+ {parameters?.legendEnabled && (
137
+ <ChartLegend
138
+ data={{
139
+ labels: data.map((series) => series.label),
140
+ colors: defaultColors,
141
+ parameters: {
142
+ textFormat: parameters?.legendTextFormat,
143
+ circleSize: parameters?.circleSize,
144
+ darkMode: parameters?.darkMode || false,
145
+ legendGap: legendGap,
146
+ legendPosition: legendPosition,
147
+ },
148
+ }}
149
+ />
150
+ )}
151
+ <div className="chart">
152
+ <Chart<KeyIndicator>
153
+ options={{
154
+ data,
155
+ primaryAxis,
156
+ secondaryAxes,
157
+ dark: parameters?.darkMode,
158
+ defaultColors: defaultColors,
159
+ // Esconder leyenda por defecto e interacciones con cursor
160
+ tooltip: {
161
+ show: false,
162
+ },
163
+ primaryCursor: false,
164
+ secondaryCursor: false,
165
+ }}
166
+ />
167
+ </div>
168
+ </div>
169
+ </div>
170
+ );
171
+ };
@@ -0,0 +1,66 @@
1
+ import React from "react";
2
+ import { TextFormat } from "@vixoniccom/modules";
3
+ import { FormattedText } from "../FormattedText";
4
+
5
+ type Props = {
6
+ data: {
7
+ labels: string[];
8
+ colors: string[];
9
+ parameters: {
10
+ textFormat?: TextFormat.Value;
11
+ circleSize?: number;
12
+ darkMode: boolean;
13
+ legendPosition: string;
14
+ legendGap: number;
15
+ };
16
+ };
17
+ };
18
+
19
+ /**
20
+ * Componente para renderizar la leyenda del gráfico según los labels de
21
+ los datos y los colores por defecto definidos.
22
+ */
23
+ export const ChartLegend: React.FunctionComponent<Props> = ({ data }) => {
24
+ const params = data.parameters;
25
+ const circleSize = params?.circleSize || 8;
26
+ const fontColor = !params?.textFormat?.fontColor
27
+ ? params?.darkMode
28
+ ? "white"
29
+ : "black"
30
+ : params?.textFormat?.fontColor;
31
+ return (
32
+ // Renderizar contenedor con margen dependiendo de la posición provista en la config.
33
+ <div
34
+ className="legend-box"
35
+ style={{
36
+ marginLeft:
37
+ params?.legendPosition === "left" ? "0px" : `${params?.legendGap}px`,
38
+ marginRight:
39
+ params?.legendPosition === "right" ? "0px" : `${params?.legendGap}px`,
40
+ }}
41
+ >
42
+ {data.labels.map((label, index) => (
43
+ // Contenedor con círculo de color y label
44
+ <div key={index} className="label-container">
45
+ <div
46
+ className="label-color"
47
+ style={{
48
+ width: `${circleSize}px`,
49
+ height: `${circleSize}px`,
50
+ backgroundColor: data.colors[index],
51
+ }}
52
+ ></div>
53
+ <div className="label-text">
54
+ <FormattedText
55
+ text={label}
56
+ format={{
57
+ ...params?.textFormat,
58
+ ...{ fontColor: fontColor },
59
+ }}
60
+ />
61
+ </div>
62
+ </div>
63
+ ))}
64
+ </div>
65
+ );
66
+ };
@@ -0,0 +1,47 @@
1
+ import React from "react";
2
+
3
+ interface Props {
4
+ paths: Array<string>;
5
+ parameters: VixonicParameters;
6
+ downloadsPath: string;
7
+ }
8
+
9
+ /**
10
+ * Componente que carga a través de <style> las fuentes obtenidas
11
+ desde la configuración
12
+ */
13
+ export const FontLoader: React.FunctionComponent<Props> = ({
14
+ paths,
15
+ parameters,
16
+ downloadsPath,
17
+ }: Props) => {
18
+ const _getValueByPath = (path: any, obj: any): any => {
19
+ const pathsArray = path.split(".");
20
+ const propertyName = pathsArray[0];
21
+ if (pathsArray.length === 1) return obj[propertyName];
22
+ else {
23
+ pathsArray.splice(0, 1);
24
+ return _getValueByPath(pathsArray.join("."), obj[propertyName]);
25
+ }
26
+ };
27
+
28
+ const fonts = paths.map((path: any) => {
29
+ try {
30
+ const fontParam = _getValueByPath(path, parameters);
31
+ const font = {
32
+ family: fontParam.filename.replace(".", "-"),
33
+ src: `${downloadsPath}/${fontParam.filename}`,
34
+ };
35
+ return `
36
+ @font-face {
37
+ font-family: "${font.family}";
38
+ src: url("${font.src}");
39
+ }
40
+ `;
41
+ } catch (err) {
42
+ return "";
43
+ }
44
+ });
45
+
46
+ return <style>{fonts}</style>;
47
+ };
@@ -0,0 +1,88 @@
1
+ import React from "react";
2
+
3
+ // Objeto con los tipos de alineaciones de texto
4
+ const alignments = {
5
+ center: "center",
6
+ left: "flex-start",
7
+ right: "flex-end",
8
+ };
9
+
10
+ // Tipado de alineación
11
+ type aligment = {
12
+ horizontal: keyof typeof alignments;
13
+ vertical: keyof typeof alignments;
14
+ };
15
+
16
+ interface Props {
17
+ format?: any;
18
+ lineHeight?: number;
19
+ style?: number;
20
+ text: string;
21
+ }
22
+
23
+ /**
24
+ * Componente para mostrar, a través de <span>, un texto que considera todo
25
+ el formato indicado en la configuración
26
+ */
27
+ export const FormattedText: React.FunctionComponent<Props> = ({
28
+ text,
29
+ format,
30
+ lineHeight,
31
+ style,
32
+ }: Props) => {
33
+ // Función para verificar si propiedad pertenece al objeto
34
+ const checkNested = (obj: any, path: string): boolean => {
35
+ const arr = path.split(".");
36
+ return arr.every((key, index) => {
37
+ if (index === arr.length - 1) return key in obj;
38
+ obj = obj[key];
39
+ return obj && typeof obj === "object";
40
+ });
41
+ };
42
+
43
+ // Función para obtener la alineación de texto basada en la configuración
44
+ const getHorizontalAlignment = (alignment: aligment) => {
45
+ if (alignment) {
46
+ const hA = alignment.horizontal;
47
+ return alignments.hasOwnProperty(hA)
48
+ ? alignments[alignment.horizontal]
49
+ : "flex-start";
50
+ }
51
+ return "flex-start";
52
+ };
53
+
54
+ const containerStyle = Object.assign(
55
+ {
56
+ display: "flex",
57
+ justifyContent: getHorizontalAlignment(format?.alignment),
58
+ flex: format?.flex || 0,
59
+ },
60
+ style
61
+ );
62
+
63
+ return (
64
+ <div style={containerStyle}>
65
+ <span
66
+ style={{
67
+ display: "inline-flex",
68
+ color: format?.fontColor || "white",
69
+ fontWeight: format?.fontWeight || "normal",
70
+ fontFamily: checkNested(format, "font.filename")
71
+ ? `"${format?.font?.filename?.replace(".", "-")}"`
72
+ : "",
73
+ fontSize: `${format?.fontSize}px` || 18,
74
+ textAlign: checkNested(format, "alignment.horizontal")
75
+ ? format?.alignment?.horizontal
76
+ : "left",
77
+ lineHeight: lineHeight || 1,
78
+ marginTop: format?.marginTop || 0,
79
+ marginLeft: format?.marginLeft || 0,
80
+ marginBottom: format?.marginBottom || 0,
81
+ marginRight: format?.marginRight || 0,
82
+ }}
83
+ >
84
+ {text}
85
+ </span>
86
+ </div>
87
+ );
88
+ };