Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Metric format converter #1321

Merged
merged 23 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
6c12783
Adding custom converter to convert sprintf-js to d3format for plotly
namnguyen20999 May 26, 2024
9b4b1a8
create a re-usable file for format converter
namnguyen20999 May 28, 2024
2a7e04b
adding unit test
namnguyen20999 May 29, 2024
7643c5a
Merge branch 'develop' into 1297-value-format
namnguyen20999 May 29, 2024
2a9876b
fix test case name
namnguyen20999 May 29, 2024
cdcd954
Merge branch '1297-value-format' of github.com:Avaiga/taipy into 1297…
namnguyen20999 May 29, 2024
95c19d1
refactoring the format & delta_format
namnguyen20999 May 29, 2024
d03df5d
Merge branch 'develop' into 1297-value-format
namnguyen20999 May 29, 2024
f762e9d
adding edge test case
namnguyen20999 May 30, 2024
32b0604
Merge branch '1297-value-format' of github.com:Avaiga/taipy into 1297…
namnguyen20999 May 30, 2024
68ca3e2
Merge branch 'develop' into 1297-value-format
namnguyen20999 May 30, 2024
9fe190a
Merge branch 'develop' into 1297-value-format
namnguyen20999 May 31, 2024
a9d3dd8
refactor code base on reviews
namnguyen20999 Jun 2, 2024
aaa2323
Merge branch 'develop' into 1297-value-format
namnguyen20999 Jun 2, 2024
6bfe97d
resolve comments
namnguyen20999 Jun 3, 2024
762cae3
resolve comments
namnguyen20999 Jun 3, 2024
c2798cc
Delete frontend/taipy-gui/public/stylekit/controls/metric.css
namnguyen20999 Jun 3, 2024
181c0be
Merge branch 'develop' into 1297-value-format
namnguyen20999 Jun 4, 2024
3693ce6
update to camelCase
namnguyen20999 Jun 4, 2024
678fa7f
update to camelCase
namnguyen20999 Jun 4, 2024
cdc0834
refactor code base on comments
namnguyen20999 Jun 4, 2024
32ade6d
Merge branch 'develop' into 1297-value-format
namnguyen20999 Jun 4, 2024
4436b1a
Merge branch 'develop' into 1297-value-format
namnguyen20999 Jun 4, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 46 additions & 42 deletions frontend/taipy-gui/src/components/Taipy/Metric.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,13 @@
* specific language governing permissions and limitations under the License.
*/

import React, {
CSSProperties,
lazy,
Suspense,
useMemo
} from 'react';
import React, {CSSProperties, lazy, Suspense, useMemo} from 'react';
import {Data} from "plotly.js";
import {
useClassNames,
useDynamicJsonProperty,
useDynamicProperty
} from "../../utils/hooks";
import {
TaipyBaseProps,
TaipyHoverProps
} from "./utils";
import Box from "@mui/material/Box";
import Skeleton from "@mui/material/Skeleton";
import {useClassNames, useDynamicJsonProperty, useDynamicProperty} from "../../utils/hooks";
import {extractPrefix, extractSuffix, sprintfToD3Converter} from "../../utils/formatConversion";
import {TaipyBaseProps, TaipyHoverProps} from "./utils";

const Plot = lazy(() => import("react-plotly.js"));

Expand All @@ -50,6 +39,8 @@ interface MetricProps extends TaipyBaseProps, TaipyHoverProps {
width?: string | number;
height?: string | number;
showValue?: boolean;
format?: string;
deltaFormat?: string;
}

const emptyLayout = {} as Record<string, Record<string, unknown>>;
Expand All @@ -68,37 +59,49 @@ const Metric = (props: MetricProps) => {
const baseLayout = useDynamicJsonProperty(props.layout, props.defaultLayout || "", emptyLayout);
const baseStyle = useDynamicJsonProperty(props.style, props.defaultStyle || "", defaultStyle);
namnguyen20999 marked this conversation as resolved.
Show resolved Hide resolved

const data = useMemo(() => ([
{
domain: {x: [0, 1], y: [0, 1]},
value: value,
type: "indicator",
mode: "gauge" + (showValue ? "+number" : "") + (delta !== undefined ? "+delta" : ""),
delta: {
reference: typeof value === 'number' && typeof delta === 'number' ? value - delta : undefined,
},
gauge: {
axis: {
range: [
typeof props.min === 'number' ? props.min : 0,
typeof props.max === 'number' ? props.max : 100
]
const data = useMemo(() => {
return [
{
domain: {x: [0, 1], y: [0, 1]},
value: value,
type: "indicator",
mode: "gauge" + (showValue ? "+number" : "") + (delta !== undefined ? "+delta" : ""),
number: {
prefix: extractPrefix(props.format),
suffix: extractSuffix(props.format),
valueformat: sprintfToD3Converter(props.format),
},
shape: props.type === "linear" ? "bullet" : "angular",
threshold: {
line: {color: "red", width: 4},
thickness: 0.75,
value: threshold
}
},
}
]), [
value,
showValue,
delta,
delta: {
reference: typeof value === 'number' && typeof delta === 'number' ? value - delta : undefined,
prefix: extractPrefix(props.deltaFormat),
suffix: extractSuffix(props.deltaFormat),
valueformat: sprintfToD3Converter(props.deltaFormat)
},
gauge: {
axis: {
range: [
props.min ?? 0,
namnguyen20999 marked this conversation as resolved.
Show resolved Hide resolved
props.max ?? 100
]
},
shape: props.type === "linear" ? "bullet" : "angular",
threshold: {
line: {color: "red", width: 4},
thickness: 0.75,
value: threshold
}
},
}
];
}, [
props.format,
props.deltaFormat,
props.min,
props.max,
props.type,
value,
showValue,
delta,
threshold
]);

Expand All @@ -119,6 +122,7 @@ const Metric = (props: MetricProps) => {
data={data as Data[]}
layout={baseLayout}
style={style}
useResizeHandler
/>
</Suspense>
</Box>
Expand Down
104 changes: 104 additions & 0 deletions frontend/taipy-gui/src/utils/formatConversion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Copyright 2021-2024 Avaiga Private Limited
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/

/**
* Regular expressions used for parsing sprintf format strings.
*/
const re = {
text: /^[^\x25]+/, // Matches non-placeholder text
modulo: /^\x25{2}/, // Matches the '%%' escape sequence
placeholder: /^\x25?(?:\.(\d+))?([b-giostuvxX])/, // Matches placeholders
};

const precisionFormat = (precision?: string, specifier?: string): string => {

Check warning on line 23 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🕹️ Function is not covered

Warning! Not covered function
// Default to precision of 2 if not specified
return "." + (precision?.slice(1) ?? "2") + specifier;

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch

Check warning on line 25 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
}

const sprintfParse = (fmt?: string): (string | { placeholder: string; })[] => {
namnguyen20999 marked this conversation as resolved.
Show resolved Hide resolved
let _fmt = fmt;
let match;
const parse_tree = [];
namnguyen20999 marked this conversation as resolved.
Show resolved Hide resolved

while (_fmt) {
if ((match = re.text.exec(_fmt)) !== null) {
// Non-placeholder text
parse_tree.push(match[0]);
} else if ((match = re.modulo.exec(_fmt)) !== null) {
// '%%' escape sequence
parse_tree.push('%');
} else if ((match = re.placeholder.exec(_fmt)) !== null) {
// Placeholder
if (match && match[0]) {
parse_tree.push({
placeholder: match[0],
});
}
}

if (match) {
_fmt = _fmt.substring(match[0].length);
}
}

return parse_tree;
}

export const sprintfToD3Converter = (fmt?: string): string => {
const sprintf_fmt_arr = sprintfParse(fmt);
namnguyen20999 marked this conversation as resolved.
Show resolved Hide resolved
const objectIndex = sprintf_fmt_arr.findIndex((element) => typeof element === 'object');
let placeholderValue;

if (typeof sprintf_fmt_arr[objectIndex] === 'object' && sprintf_fmt_arr[objectIndex] !== null) {
placeholderValue = (sprintf_fmt_arr[objectIndex] as { placeholder: string }).placeholder;
}

if (placeholderValue === undefined) {
namnguyen20999 marked this conversation as resolved.
Show resolved Hide resolved
return "";
}

return placeholderValue.replace(/%([0-9]*)([.][0-9]+)?([bdieufgoxX])/g, (match, width, precision, type) => {

Check warning on line 70 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🕹️ Function is not covered

Warning! Not covered function
switch (type) {
case "b":
case "d":
case "e":
case "o":
case "x":
case "X":
return type;
case "i":
return "d";
case "f":
return precisionFormat(precision, "f");
case "g":
return precisionFormat(precision, "g");
case "u":
return "("
default:
return "";
}
});

Check warning on line 90 in frontend/taipy-gui/src/utils/formatConversion.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

export const extractPrefix = (fmt?: string): string => {
const sprintf_fmt_arr = sprintfParse(fmt);
const objectIndex = sprintf_fmt_arr.findIndex((element) => typeof element === 'object');
namnguyen20999 marked this conversation as resolved.
Show resolved Hide resolved
return sprintf_fmt_arr.slice(0, objectIndex).join('');
}

export const extractSuffix = (fmt?: string): string => {
const sprintf_fmt_arr = sprintfParse(fmt);
const objectIndex = sprintf_fmt_arr.findIndex((element) => typeof element === 'object');
return sprintf_fmt_arr.slice(objectIndex + 1).join('');
}

2 changes: 2 additions & 0 deletions taipy/gui/_renderers/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,8 @@ class _Factory:
("width", PropertyType.string_or_number),
("height", PropertyType.string_or_number),
("show_value", PropertyType.boolean, True),
("format", PropertyType.string),
("delta_format", PropertyType.string),
]
),
"navbar": lambda gui, control_type, attrs: _Builder(
Expand Down
10 changes: 10 additions & 0 deletions taipy/gui/viselements.json
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,16 @@
"type": "str|number",
"default_value": "None",
"doc": "The height, in CSS units, of the metric."
},
{
"name": "format",
"type": "str",
"doc": "The format to use when displaying the value.<br/>This uses the <code>printf</code> syntax."
},
{
"name": "delta_format",
"type": "str",
"doc": "The format to use when displaying the delta value.<br/>This uses the <code>printf</code> syntax."
}
]
}
Expand Down
Loading
Loading