All files / src attributeDisplayWidgetUtils.ts

91.95% Statements 160/174
79.64% Branches 133/167
100% Functions 21/21
97.22% Lines 140/144

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286                    19x 80x 80x 80x 80x 80x 1x   79x 79x 79x 80x     19x 12x 12x 4x     19x 4x 4x   3x 3x 2x 2x 1x 1x 1x 1x 1x   1x 1x 1x 1x 2x     1x     1x 1x 1x 1x 1x 4x 4x     19x 3x 3x     19x 1x 1x 1x   1x 1x 1x     1x     1x 1x 1x     19x 4x 3x 3x   3x 3x             3x 3x 3x         19x 16x 2x 2x   2x 2x             2x 2x 2x         19x 137x             19x 137x       19x 21x 2x 2x 2x 1x 1x         19x         40x 19x 19x 19x 19x 2x     19x 47x 44x 43x 36x 16x 2x 2x   1x       19x   46x   19x 5x 5x 5x 5x 4x 4x           19x 14x 12x 2x 2x 2x   11x     19x         21x 20x         21x 1x     20x 19x           1x           19x 43x 43x 43x 3x           19x 46x   1x   3x     42x       19x 48x   3x   1x     44x       19x               47x                          
import type { CSSProperties } from 'react';
import {
  coerceNumber,
  STATE_COLORS_HEX,
  STATE_COLORS_TEXT,
  TABLEAU_10_HEX
} from '@ska-octopus-widget-sdk/widget-sdk';
import type { AttributeDisplayWidgetProps } from './AttributeDisplayWidget.types';
import type { AttributeSelection } from './AttributeDisplayWidget.types';
 
export const parseFullName = (fullName: string) => {
  const trimmed = String(fullName ?? '').trim();
  const routed = /^(.+):\/\/(.+)$/.exec(trimmed);
  const target = routed?.[2] ? String(routed[2]) : trimmed;
  const parts = target.split('/').filter(Boolean);
  if (parts.length < 2) {
    return { device: target, attribute: '', deviceTail: target };
  }
  const attribute = parts[parts.length - 1];
  const device = parts.slice(0, -1).join('/');
  const deviceTail = parts[parts.length - 2] ?? device;
  return { device, attribute, deviceTail };
};
 
export const formatAttributeLabel = (attribute: string) => {
  Iif (!attribute) return '';
  if (/[A-Z]/.test(attribute)) return attribute;
  return attribute.charAt(0).toUpperCase() + attribute.slice(1);
};
 
export const parseCssColor = (input: string) => {
  const value = input.trim();
  if (!value) return null;
 
  const hexMatch = value.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
  if (hexMatch) {
    const hex = hexMatch[1];
    if (hex.length === 3 || hex.length === 4) {
      const r = parseInt(hex[0] + hex[0], 16);
      const g = parseInt(hex[1] + hex[1], 16);
      const b = parseInt(hex[2] + hex[2], 16);
      const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
      return { r, g, b, a };
    }
    const r = parseInt(hex.slice(0, 2), 16);
    const g = parseInt(hex.slice(2, 4), 16);
    const b = parseInt(hex.slice(4, 6), 16);
    const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
    return { r, g, b, a };
  }
 
  const rgbMatch = value.match(
    /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})(?:\s*,\s*(\d*\.?\d+))?\s*\)$/i
  );
  Iif (!rgbMatch) return null;
  const r = Math.min(255, Math.max(0, Number(rgbMatch[1])));
  const g = Math.min(255, Math.max(0, Number(rgbMatch[2])));
  const b = Math.min(255, Math.max(0, Number(rgbMatch[3])));
  const alphaRaw = rgbMatch[4] == null ? 1 : Number(rgbMatch[4]);
  const a = Number.isFinite(alphaRaw) ? Math.min(1, Math.max(0, alphaRaw)) : 1;
  return { r, g, b, a };
};
 
const relativeLuminance = (channel: number) => {
  const s = channel / 255;
  return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
};
 
export const pickContrastingTextColor = (background: string | undefined) => {
  Iif (!background) return '#111111';
  const parsed = parseCssColor(background);
  Iif (!parsed) return '#111111';
 
  const blendedR = parsed.r * parsed.a + 255 * (1 - parsed.a);
  const blendedG = parsed.g * parsed.a + 255 * (1 - parsed.a);
  const blendedB = parsed.b * parsed.a + 255 * (1 - parsed.a);
 
  const lum =
    0.2126 * relativeLuminance(blendedR) +
    0.7152 * relativeLuminance(blendedG) +
    0.0722 * relativeLuminance(blendedB);
  const contrastWhite = 1.05 / (lum + 0.05);
  const contrastBlack = (lum + 0.05) / 0.05;
  return contrastBlack >= contrastWhite ? '#111111' : '#ffffff';
};
 
export const resolveStateBackgroundColor = (value: unknown) => {
  if (typeof value !== 'string') return undefined;
  const raw = value.trim();
  Iif (!raw) return undefined;
 
  const upper = raw.toUpperCase();
  const lookupKeys = [
    upper,
    upper.replace(/\s+/g, '_'),
    upper.replace(/_/g, ' '),
    upper.replace(/[-\s]+/g, '_')
  ];
 
  for (const key of lookupKeys) {
    const color = (STATE_COLORS_HEX as Record<string, string>)[key];
    Eif (typeof color === 'string' && color.trim()) return color;
  }
  return undefined;
};
 
export const resolveStateTextColor = (value: unknown) => {
  if (typeof value !== 'string') return undefined;
  const raw = value.trim();
  Iif (!raw) return undefined;
 
  const upper = raw.toUpperCase();
  const lookupKeys = [
    upper,
    upper.replace(/\s+/g, '_'),
    upper.replace(/_/g, ' '),
    upper.replace(/[-\s]+/g, '_')
  ];
 
  for (const key of lookupKeys) {
    const color = STATE_COLORS_TEXT[key as keyof typeof STATE_COLORS_TEXT];
    Eif (typeof color === 'string' && color.trim()) return color;
  }
  return undefined;
};
 
export const canonicalDevice = (device: string) =>
  String(device ?? '')
    .trim()
    .replace(/^tango:\/\/[^/]+\/(.+)$/i, '$1')
    .replace(/^(.+):\/\/(.+)$/i, '$2')
    .replace(/\/+$/, '')
    .toLowerCase();
 
export const enumKeyFor = (device: string, attribute: string) =>
  `${canonicalDevice(device)}::${String(attribute ?? '')
    .trim()
    .toLowerCase()}`;
 
export const coerceEnumIndex = (value: unknown): number | null => {
  if (typeof value === 'number' && Number.isFinite(value)) return value;
  Eif (typeof value === 'string') {
    const trimmed = value.trim();
    if (trimmed === '') return null;
    const num = Number(trimmed);
    Eif (Number.isFinite(num)) return num;
  }
  return null;
};
 
export const translateEnumValue = (
  value: unknown,
  labels: string[] | null | undefined,
  useEnumLabels: boolean
): unknown => {
  if (!useEnumLabels || !Array.isArray(labels) || labels.length === 0) return value;
  const idx = coerceEnumIndex(value);
  Iif (idx == null) return value;
  const label = labels[idx];
  if (typeof label === 'string' && label.trim() !== '') return label;
  return value;
};
 
export const formatValue = (value: unknown): string => {
  if (value === true) return 'TRUE';
  if (value === false) return 'FALSE';
  if (value == null) return '-';
  if (typeof value === 'string') return value;
  if (typeof value === 'number') return Number.isFinite(value) ? String(value) : '-';
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
};
 
export const isJsonTreeMode = (
  viewMode: AttributeDisplayWidgetProps['devStringViewMode'] | undefined
) => viewMode != null && viewMode !== 'plain';
 
export const tryParseJsonString = (value: unknown): unknown | null => {
  Iif (typeof value !== 'string') return null;
  const trimmed = value.trim();
  Iif (!trimmed) return null;
  if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return null;
  try {
    return JSON.parse(trimmed);
  } catch {
    return null;
  }
};
 
export const coerceComparableNumber = (value: unknown): number | null => {
  if (typeof value === 'boolean') return value ? 1 : 0;
  if (typeof value === 'string') {
    const trimmed = value.trim().toLowerCase();
    Iif (trimmed === 'true') return 1;
    if (trimmed === 'false') return 0;
  }
  return coerceNumber(value);
};
 
export const normalizeSelection = (
  attributes: AttributeSelection[] | undefined,
  tangoDB: string | undefined,
  expression: string | undefined
) => {
  const first = attributes?.find((entry) =>
    typeof entry === 'string'
      ? entry.trim() !== ''
      : typeof entry?.attribute === 'string' && entry.attribute.trim() !== ''
  );
 
  if (typeof first === 'string') {
    return { endpoint: tangoDB ?? '', attribute: first.trim() };
  }
 
  if (first && typeof first === 'object') {
    return {
      endpoint: typeof first.endpoint === 'string' ? first.endpoint : (tangoDB ?? ''),
      attribute: typeof first.attribute === 'string' ? first.attribute.trim() : ''
    };
  }
 
  return {
    endpoint: tangoDB ?? '',
    attribute: typeof expression === 'string' ? expression.trim() : ''
  };
};
 
export const splitRoutedSelection = (value: string) => {
  const trimmed = String(value ?? '').trim();
  const match = /^(.+):\/\/(.+)$/.exec(trimmed);
  if (!match) return { endpoint: '', attribute: trimmed };
  return {
    endpoint: String(match[1] ?? '').trim(),
    attribute: String(match[2] ?? '').trim()
  };
};
 
export const mapHorizontal = (value: AttributeDisplayWidgetProps['horizontalAlign']) => {
  switch (value) {
    case 'left':
      return 'flex-start';
    case 'right':
      return 'flex-end';
    case 'center':
    default:
      return 'center';
  }
};
 
export const mapVertical = (value: AttributeDisplayWidgetProps['verticalAlign']) => {
  switch (value) {
    case 'top':
      return 'flex-start';
    case 'bottom':
      return 'flex-end';
    case 'center':
    default:
      return 'center';
  }
};
 
export const buildContainerStyle = (
  effectiveTextColor: string | undefined,
  effectiveTitleColor: string | undefined,
  effectiveMutedColor: string | undefined,
  effectiveBackgroundColor: string | undefined,
  fontSize: string | undefined,
  colorJsonValuesByType: boolean
) =>
  ({
    '--text': effectiveTextColor || undefined,
    '--title-color': effectiveTitleColor || undefined,
    '--label-color': effectiveTitleColor || undefined,
    '--muted': effectiveMutedColor,
    '--card-bg': effectiveBackgroundColor || undefined,
    '--value-type-string': colorJsonValuesByType ? TABLEAU_10_HEX.pink : undefined,
    '--value-type-number': colorJsonValuesByType ? TABLEAU_10_HEX.green : undefined,
    '--value-type-boolean': colorJsonValuesByType ? STATE_COLORS_HEX.WARNING : undefined,
    '--value-type-null': colorJsonValuesByType ? STATE_COLORS_HEX.UNKNOWN : undefined,
    '--value-type-other': colorJsonValuesByType ? TABLEAU_10_HEX.blue : undefined,
    fontSize
  }) as CSSProperties;