From 49aaa91d2e12679a2dfb0b5c5b224017803ce7e9 Mon Sep 17 00:00:00 2001 From: Alejandro Gallardo Escobar Date: Mon, 11 Feb 2019 17:35:16 +0100 Subject: [PATCH] WIP: Visual Console Refactor Former-commit-id: c82cb8454f12caa66e2b06668f1d486a379be838 --- visual_console/src/VisualConsoleItem.ts | 2 +- visual_console/src/items/StaticGraph.ts | 47 +++++++++++++++++++++++-- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/visual_console/src/VisualConsoleItem.ts b/visual_console/src/VisualConsoleItem.ts index d172fa7f13..7895854a14 100644 --- a/visual_console/src/VisualConsoleItem.ts +++ b/visual_console/src/VisualConsoleItem.ts @@ -27,7 +27,7 @@ export type ItemClickEvent = { * This will allow us to ensure the type safety. * * @param data Raw object. - * @return An object representing the size. + * @return An object representing the item props. * @throws Will throw a TypeError if some property * is missing from the raw object or have an invalid type. */ diff --git a/visual_console/src/items/StaticGraph.ts b/visual_console/src/items/StaticGraph.ts index fe562e9c74..81b89bd591 100644 --- a/visual_console/src/items/StaticGraph.ts +++ b/visual_console/src/items/StaticGraph.ts @@ -1,7 +1,12 @@ -import { WithModuleProps, LinkedVisualConsoleProps } from "../types"; +import { + WithModuleProps, + LinkedVisualConsoleProps, + UnknownObject +} from "../types"; import VisualConsoleItem, { - VisualConsoleItemProps + VisualConsoleItemProps, + itemPropsDecoder } from "../VisualConsoleItem"; export type StaticGraphProps = { @@ -10,6 +15,44 @@ export type StaticGraphProps = { } & VisualConsoleItemProps & (WithModuleProps | LinkedVisualConsoleProps); +/** + * Extract a valid enum value from a raw unknown value. + * @param showLastValueTooltip Raw value. + */ +const parseShowLastValueTooltip = (showLastValueTooltip: any) => { + switch (showLastValueTooltip) { + case "default": + case "enabled": + case "disabled": + return showLastValueTooltip; + default: + return "default"; + } +}; + +/** + * Build a valid typed object from a raw object. + * This will allow us to ensure the type safety. + * + * @param data Raw object. + * @return An object representing the static graph props. + * @throws Will throw a TypeError if some property + * is missing from the raw object or have an invalid type. + */ +export function staticGraphPropsDecoder( + data: UnknownObject +): StaticGraphProps | never { + if (typeof data.imageSrc !== "string" || data.imageSrc.length === 0) { + throw new TypeError("invalid image src."); + } + + return { + imageSrc: data.imageSrc, + showLastValueTooltip: parseShowLastValueTooltip(data.showLastValueTooltip), + ...itemPropsDecoder(data) // Object spread. It will merge the properties of the two objects. + }; +} + export default class StaticGraph extends VisualConsoleItem { createDomElement(): HTMLElement { const img: HTMLImageElement = document.createElement("img");