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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 | 18x 42x 42x 42x 46x 46x 46x 46x 46x 46x 42x 18x 44x 44x 44x 8x 8x 36x 36x 44x 18x 11x 6x 6x 6x 6x 12x 6x 18x 18x 4x 4x 18x 18x 18x 18x 4x 18x 44x 44x 44x 44x 44x 44x 20x 44x 44x 44x 44x 42x 44x 44x 44x 17x 44x 16x 44x 16x 44x 17x 44x 16x 16x 17x 17x 17x 16x 44x 44x 44x 44x 44x 15x 44x 15x 44x 44x 44x 17x 17x 17x 17x 17x 44x 44x 39x 39x 39x 39x 44x 18x 44x 19x 19x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 3x 44x 39x 39x 31x 31x 36x 36x 36x 36x 16x 31x 44x 34x 34x 11x 11x 44x 44x 44x 44x 44x 44x 40x 44x 36x 32x 6x 2x 44x 44x 44x 44x 44x 44x 44x 44x 16x 13x 13x 12x 10x 10x 2x 1x 44x 44x 42x 34x 34x 34x 34x 8x 16x 16x 16x 8x 44x 16x 1x 44x 44x 44x 42x 44x 19x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 44x 44x 2x 2x 42x 6x 44x 15x 1x 44x 15x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x | import { useEffect, useMemo, useState } from 'react';
import type { CSSProperties } from 'react';
import { useQuery } from '@apollo/client';
import {
evaluateExpression,
formatInputFormattedTemplate,
normalizeTangoAttributeInputs,
parseExpression,
useHostVariables,
useReplayMode,
useStream,
useWidgetRuntimeSnapshot,
useWidgetLayout,
useWidgetRefreshRate
} from '@ska-octopus-widget-sdk/widget-sdk';
import { pollingDocs, streamDocs } from './graphql/ops';
import type { AttributeDisplayWidgetProps } from './AttributeDisplayWidget.types';
import {
buildContainerStyle,
coerceComparableNumber,
enumKeyFor,
formatAttributeLabel,
formatValue,
isJsonTreeMode,
mapHorizontal,
mapVertical,
normalizeSelection,
parseFullName,
pickContrastingTextColor,
resolveStateBackgroundColor,
resolveStateTextColor,
splitRoutedSelection,
tryParseJsonString,
translateEnumValue
} from './attributeDisplayWidgetUtils';
type EnumLabels = string[] | null | undefined;
type PollingAttribute = {
device?: string;
name?: string;
attribute?: string;
value?: unknown;
enumLabels?: EnumLabels;
};
type StreamAttribute = {
device?: string;
attribute?: string;
name?: string;
value?: unknown;
};
const buildRawValueMap = (
payload: Array<PollingAttribute | StreamAttribute>,
allowedKeys?: Set<string>
) => {
const map = new Map<string, unknown>();
Iif (!Array.isArray(payload)) return map;
for (const attr of payload) {
const device = attr.device;
const name =
(attr as PollingAttribute).name ??
(attr as StreamAttribute).attribute ??
(attr as StreamAttribute).name;
Iif (!device || !name) continue;
const key = enumKeyFor(device, name);
Iif (allowedKeys && !allowedKeys.has(key)) continue;
map.set(key, attr.value);
}
return map;
};
const buildDisplayValueMap = (
rawMap: Map<string, unknown>,
enumLabelsMap: Map<string, string[]>,
useEnumLabels: boolean
) => {
const map = new Map<string, unknown>();
for (const [key, value] of rawMap) {
if (!useEnumLabels) {
map.set(key, value);
continue;
}
const labels = enumLabelsMap.get(key);
map.set(key, translateEnumValue(value, labels, useEnumLabels));
}
return map;
};
const areStringArrayMapsEqual = (a: Map<string, string[]>, b: Map<string, string[]>) => {
if (a.size !== b.size) return false;
for (const [key, value] of a) {
const other = b.get(key);
Iif (!other || other.length !== value.length) return false;
for (let i = 0; i < value.length; i += 1) {
Iif (other[i] !== value[i]) return false;
}
}
return true;
};
const normalizeStreamPayload = (data: any, fieldName: string): StreamAttribute[] => {
if (!data) return [];
const direct = (data as any)[fieldName];
const wrapped = (data as any)?.data?.[fieldName];
const fallbackRoot = Array.isArray(data) ? data : (Object.values(data)[0] as any);
const nestedFallback = (fallbackRoot as any)?.[fieldName];
const root = direct ?? wrapped ?? nestedFallback ?? fallbackRoot;
Iif (!root) return [];
return Array.isArray(root) ? root : [root];
};
export const useAttributeDisplayWidgetData = (config: AttributeDisplayWidgetProps) => {
const {
instanceId,
attributes,
tangoDB,
expression,
useLiveData = true,
useEnumLabels = true,
title,
label,
backgroundColor,
useStateBackgroundColor = false,
showStateChip = false,
conditionalBackgroundValue,
conditionalBackgroundOperator = '>=',
conditionalBackgroundColor,
valueColor,
textColor,
titleColor,
labelColor,
fontSize,
labelPosition = 'top',
horizontalAlign = 'center',
verticalAlign = 'center',
devStringViewMode = 'plain',
colorJsonValuesByType = true
} = config;
const variables = useHostVariables();
const refresh = useWidgetRefreshRate(instanceId ?? 'attributeDisplay');
const widgetLayout = useWidgetLayout(instanceId ?? 'attributeDisplay');
const replayModeActive = useReplayMode();
const selection = useMemo(
() => normalizeSelection(attributes, tangoDB, expression),
[attributes, tangoDB, expression]
);
const resolvedSelection = useMemo(() => {
const resolved = normalizeTangoAttributeInputs({
attributes: [{ endpoint: selection.endpoint ?? '', attribute: selection.attribute ?? '' }],
fallbackEndpoint: tangoDB,
variables
});
const routed = String(resolved[0] ?? '').trim();
if (!routed) return { endpoint: '', attribute: '' };
return splitRoutedSelection(routed);
}, [selection.endpoint, selection.attribute, tangoDB, variables]);
const expressionSource = resolvedSelection.attribute;
const expressionInfo = useMemo(() => parseExpression(expressionSource), [expressionSource]);
const fullNameList = useMemo(
() => expressionInfo.refs.map((name) => name.trim()).filter(Boolean),
[expressionInfo.refs]
);
const isSumExpression = useMemo(
() => expressionSource.trim().toLowerCase().startsWith('sum('),
[expressionSource]
);
const varsNorm = useMemo(
() => ({ endpoint: resolvedSelection.endpoint || undefined, fullNames: fullNameList }),
[resolvedSelection.endpoint, fullNameList]
);
const fullNameKey = useMemo(
() =>
`${resolvedSelection.endpoint || ''}|${fullNameList.map((name) => name.trim()).join('|')}`,
[resolvedSelection.endpoint, fullNameList]
);
const wantedKeys = useMemo(() => {
const keys = new Set<string>();
for (const fullName of fullNameList) {
const { device, attribute } = parseFullName(fullName);
Iif (!device || !attribute) continue;
keys.add(enumKeyFor(device, attribute));
}
return keys;
}, [fullNameList]);
const pollEnabled =
!replayModeActive && fullNameList.length > 0 && (!useLiveData || useEnumLabels);
const streamEnabled = !replayModeActive && useLiveData && fullNameList.length > 0;
const pollResultNorm = useQuery(pollingDocs[0], {
variables: varsNorm,
pollInterval: useLiveData ? 0 : refresh * 1000,
fetchPolicy: 'network-only',
notifyOnNetworkStatusChange: true,
skip: replayModeActive || !pollEnabled || fullNameList.length === 0
});
const [liveRawValueMap, setLiveRawValueMap] = useState<Map<string, unknown>>(() => new Map());
const [runtimeRawValueMap, setRuntimeRawValueMap] = useState<Map<string, unknown>>(
() => new Map()
);
const [runtimeEnumLabelsMap, setRuntimeEnumLabelsMap] = useState<Map<string, string[]>>(
() => new Map()
);
const [hasLivePayload, setHasLivePayload] = useState(false);
const snapshotInstanceId = typeof instanceId === 'string' ? instanceId.trim() : '';
useEffect(() => {
Iif (replayModeActive) return;
setLiveRawValueMap(new Map());
setRuntimeRawValueMap(new Map());
setRuntimeEnumLabelsMap(new Map());
setHasLivePayload(false);
}, [fullNameKey, useLiveData, replayModeActive]);
const streamResultNorm = useStream({
document: streamDocs[0],
variables: varsNorm,
onData: (incoming: any) => {
if (replayModeActive || !useLiveData) return;
const attrs = normalizeStreamPayload(incoming, 'tangoAttributes');
if (!Array.isArray(attrs) || attrs.length === 0) return;
let sawRelevant = false;
setLiveRawValueMap((prev) => {
let updated = false;
const next = new Map(prev);
for (const attr of attrs) {
const device = attr.device;
const name = attr.attribute ?? attr.name;
if (!device || !name) continue;
const key = enumKeyFor(device, name);
if (wantedKeys.size > 0 && !wantedKeys.has(key)) continue;
sawRelevant = true;
if (!prev.has(key) || prev.get(key) !== attr.value) {
next.set(key, attr.value);
updated = true;
}
}
return updated ? next : prev;
});
if (sawRelevant) setHasLivePayload(true);
},
coalesce: !!streamEnabled,
client: streamEnabled && fullNameList.length ? undefined : null,
replaySnapshot: {
instanceId,
key: 'attribute-display:stream'
}
} as any);
const pollingAttributes = useMemo(() => {
const attrs: PollingAttribute[] = [];
const data = pollResultNorm.data?.attributes;
if (Array.isArray(data)) attrs.push(...data);
return attrs;
}, [pollResultNorm.data]);
const streamAttributes = useMemo(
() => normalizeStreamPayload(streamResultNorm.data, 'tangoAttributes'),
[streamResultNorm.data]
);
useEffect(() => {
Iif (replayModeActive) return;
if (!useLiveData) return;
if (!Array.isArray(streamAttributes) || streamAttributes.length === 0) return;
let sawRelevant = false;
setLiveRawValueMap((prev) => {
let updated = false;
const next = new Map(prev);
for (const attr of streamAttributes) {
const device = attr.device;
const name = attr.attribute ?? attr.name;
Iif (!device || !name) continue;
const key = enumKeyFor(device, name);
Iif (wantedKeys.size > 0 && !wantedKeys.has(key)) continue;
sawRelevant = true;
if (!prev.has(key) || prev.get(key) !== attr.value) {
next.set(key, attr.value);
updated = true;
}
}
return updated ? next : prev;
});
Iif (sawRelevant) setHasLivePayload(true);
}, [streamAttributes, useLiveData, wantedKeys, replayModeActive]);
const enumLabelsMap = useMemo(() => {
const map = new Map<string, string[]>();
if (!useEnumLabels) return map;
Iif (!Array.isArray(pollingAttributes)) return map;
for (const attr of pollingAttributes) {
const device = attr.device;
const name = attr.name ?? attr.attribute;
const labels = attr.enumLabels;
if (!device || !name || !Array.isArray(labels) || labels.length === 0) continue;
map.set(enumKeyFor(device, name), labels);
}
return map;
}, [pollingAttributes, useEnumLabels]);
useEffect(() => {
Iif (replayModeActive) return;
if (enumLabelsMap.size === 0) return;
setRuntimeEnumLabelsMap((prev) =>
areStringArrayMapsEqual(prev, enumLabelsMap) ? prev : new Map(enumLabelsMap)
);
}, [enumLabelsMap, replayModeActive]);
const streamStatus =
fullNameList.length && streamEnabled ? (streamResultNorm.status ?? 'idle') : 'idle';
const pollRefreshing =
fullNameList.length > 0 && (pollResultNorm.loading || pollResultNorm.networkStatus === 6);
const pollError = replayModeActive
? undefined
: fullNameList.length > 0
? pollResultNorm.error
: undefined;
const loading = replayModeActive
? false
: useLiveData
? streamStatus === 'loading'
: pollRefreshing;
const error = useLiveData
? replayModeActive
? undefined
: streamStatus === 'failed'
? streamResultNorm.error
: undefined
: pollError;
const pollingRawValueMap = useMemo(
() => buildRawValueMap(pollingAttributes, wantedKeys),
[pollingAttributes, wantedKeys]
);
const effectiveLiveRawValueMap = useMemo(() => {
if (liveRawValueMap.size > 0) return liveRawValueMap;
if (!useLiveData) return liveRawValueMap;
if (!Array.isArray(streamAttributes) || streamAttributes.length === 0) return liveRawValueMap;
return buildRawValueMap(streamAttributes, wantedKeys);
}, [liveRawValueMap, streamAttributes, useLiveData, wantedKeys]);
const rawValueMap = useMemo(
() => (useLiveData ? effectiveLiveRawValueMap : pollingRawValueMap),
[effectiveLiveRawValueMap, pollingRawValueMap, useLiveData]
);
const effectiveRawValueMap =
replayModeActive && runtimeRawValueMap.size > 0 ? runtimeRawValueMap : rawValueMap;
const effectiveEnumLabelsMap = enumLabelsMap.size > 0 ? enumLabelsMap : runtimeEnumLabelsMap;
const displayValueMap = useMemo(
() => buildDisplayValueMap(effectiveRawValueMap, effectiveEnumLabelsMap, useEnumLabels),
[effectiveRawValueMap, effectiveEnumLabelsMap, useEnumLabels]
);
useWidgetRuntimeSnapshot(snapshotInstanceId || undefined, {
capture: () => ({
attributeDisplay: {
rawValueMap: Array.from(effectiveRawValueMap.entries()),
enumLabelsMap: Array.from(effectiveEnumLabelsMap.entries()),
hasLivePayload
}
}),
apply: (snapshot) => {
const payload = (snapshot as any)?.attributeDisplay;
if (!payload || typeof payload !== 'object') return;
const rawEntries = Array.isArray(payload.rawValueMap) ? payload.rawValueMap : [];
const enumEntries = Array.isArray(payload.enumLabelsMap) ? payload.enumLabelsMap : [];
if (rawEntries.length > 0) {
const nextRaw = new Map(rawEntries as Array<[string, unknown]>);
setRuntimeRawValueMap(nextRaw);
setLiveRawValueMap(nextRaw);
}
if (enumEntries.length > 0) {
setRuntimeEnumLabelsMap(new Map(enumEntries as Array<[string, string[]]>));
}
setHasLivePayload(Boolean(payload.hasLivePayload || rawEntries.length > 0));
}
});
const labelTemplate = useMemo(() => {
if (title != null) return title;
Iif (label != null) return label.trim() ? label : '';
if (expressionInfo.refs.length === 0) return '';
if (expressionInfo.isSingleRef) {
const { device, attribute, deviceTail } = parseFullName(expressionInfo.refs[0]);
return attribute ? `${deviceTail}/${formatAttributeLabel(attribute)}` : device;
}
if (isSumExpression) return 'Sum';
return 'Result';
}, [expressionInfo, isSumExpression, title, label]);
const resolvedValue = useMemo(() => {
if (expressionInfo.refs.length === 0) return { raw: null, formatted: '-' };
if (expressionInfo.isSingleRef) {
const { device, attribute } = parseFullName(expressionInfo.refs[0]);
const key = enumKeyFor(device, attribute);
const value = displayValueMap.has(key)
? displayValueMap.get(key)
: effectiveRawValueMap.get(key);
return { raw: value ?? null, formatted: formatValue(value) };
}
const result = evaluateExpression(expressionInfo, (ref) => {
const { device, attribute } = parseFullName(ref);
Iif (!device || !attribute) return undefined;
return effectiveRawValueMap.get(enumKeyFor(device, attribute));
});
return { raw: result.value, formatted: formatValue(result.value) };
}, [displayValueMap, effectiveRawValueMap, expressionInfo]);
const legendFullName = useMemo(() => {
if (expressionInfo.refs.length > 0) return expressionInfo.refs[0];
return expressionSource;
}, [expressionInfo.refs, expressionSource]);
const displayLabel = useMemo(() => {
const template = String(labelTemplate ?? '');
if (!template) return '';
return formatInputFormattedTemplate({
template,
fallback: template,
variables,
legendFullName,
legendValue: resolvedValue.raw
});
}, [labelTemplate, legendFullName, resolvedValue.raw, variables]);
const matchesConditionalBackground = useMemo(() => {
if (!conditionalBackgroundColor) return false;
Iif (conditionalBackgroundValue == null || conditionalBackgroundValue === '') return false;
const leftValue = resolvedValue.raw;
Iif (leftValue == null) return false;
const leftNumber = coerceComparableNumber(leftValue);
const rightNumber = coerceComparableNumber(conditionalBackgroundValue);
Eif (leftNumber != null && rightNumber != null) {
switch (conditionalBackgroundOperator) {
case '>':
return leftNumber > rightNumber;
case '>=':
return leftNumber >= rightNumber;
case '<':
return leftNumber < rightNumber;
case '<=':
return leftNumber <= rightNumber;
case '!=':
return leftNumber !== rightNumber;
case '==':
default:
return leftNumber === rightNumber;
}
}
if (conditionalBackgroundOperator === '!=' || conditionalBackgroundOperator === '==') {
const leftText = String(leftValue);
const rightText = String(conditionalBackgroundValue);
return conditionalBackgroundOperator === '!='
? leftText !== rightText
: leftText === rightText;
}
return false;
}, [
conditionalBackgroundColor,
conditionalBackgroundValue,
conditionalBackgroundOperator,
resolvedValue.raw
]);
let effectiveBackgroundColor = backgroundColor;
if (useStateBackgroundColor) {
const stateValue =
typeof resolvedValue.raw === 'string' ? resolvedValue.raw : resolvedValue.formatted;
effectiveBackgroundColor = resolveStateBackgroundColor(stateValue) ?? backgroundColor;
} else if (matchesConditionalBackground && conditionalBackgroundColor) {
effectiveBackgroundColor = conditionalBackgroundColor;
}
const stateValueForColors = useMemo(() => {
if (!useStateBackgroundColor) return undefined;
return typeof resolvedValue.raw === 'string' ? resolvedValue.raw : resolvedValue.formatted;
}, [resolvedValue.formatted, resolvedValue.raw, useStateBackgroundColor]);
const stateTextColor = useMemo(
() => resolveStateTextColor(stateValueForColors),
[stateValueForColors]
);
const effectiveTextColor = useStateBackgroundColor
? (stateTextColor ?? pickContrastingTextColor(effectiveBackgroundColor))
: (valueColor ?? textColor);
const effectiveTitleColor = useStateBackgroundColor
? effectiveTextColor
: (titleColor ?? labelColor);
const effectiveMutedColor = useStateBackgroundColor ? effectiveTextColor : undefined;
const isHorizontalLayout = labelPosition === 'left' || labelPosition === 'right';
const isCenterLayout = labelPosition === 'center';
const justifyContent = isHorizontalLayout
? mapHorizontal(horizontalAlign)
: mapVertical(verticalAlign);
const alignItems = isHorizontalLayout
? mapVertical(verticalAlign)
: mapHorizontal(horizontalAlign);
const centerLayoutAlign = 'center' as const;
const resolvedTextAlign: 'left' | 'center' | 'right' = isCenterLayout
? 'center'
: horizontalAlign === 'left'
? 'left'
: horizontalAlign === 'right'
? 'right'
: 'center';
const containerStyle = buildContainerStyle(
effectiveTextColor || undefined,
effectiveTitleColor || undefined,
effectiveMutedColor,
effectiveBackgroundColor || undefined,
fontSize,
colorJsonValuesByType
);
const measuredHeight = Number(widgetLayout?.height ?? 0);
const measuredWidth = Number(widgetLayout?.width ?? 0);
const jsonTreeEnabled = isJsonTreeMode(devStringViewMode);
const parsedJsonValue = jsonTreeEnabled ? tryParseJsonString(resolvedValue.raw) : null;
const isMultilineValue =
parsedJsonValue != null ||
resolvedValue.formatted.includes('\n') ||
resolvedValue.formatted.length > 80;
const effectiveJustifyContent = isCenterLayout
? mapVertical(verticalAlign)
: isMultilineValue && !isHorizontalLayout
? 'flex-start'
: justifyContent;
const effectiveAlignItems = isCenterLayout
? centerLayoutAlign
: isMultilineValue && isHorizontalLayout
? 'flex-start'
: alignItems;
const contentScrollStyle = {
maxHeight: measuredHeight > 0 ? `${Math.max(24, Math.floor(measuredHeight - 4))}px` : undefined,
maxWidth: measuredWidth > 0 ? `${Math.max(24, Math.floor(measuredWidth - 4))}px` : undefined
} as CSSProperties;
const contentStyle = {
justifyContent: effectiveJustifyContent,
alignItems: effectiveAlignItems,
textAlign: isCenterLayout ? 'center' : resolvedTextAlign
} as CSSProperties;
const showInitialLoading =
loading && effectiveRawValueMap.size === 0 && !(useLiveData && hasLivePayload);
return {
loading,
error,
hasLivePayload,
showInitialLoading,
expressionCount: expressionInfo.refs.length,
displayLabel,
value: resolvedValue.formatted,
rawValue: resolvedValue.raw,
parsedJsonValue,
jsonTreeEnabled,
devStringViewMode,
showStateChip,
resolvedValue,
refreshBadgeText: useLiveData ? 'Subscribing…' : 'Refreshing…',
showRefreshBadge: loading,
isHorizontalLayout,
containerStyle,
contentStyle,
contentScrollStyle,
labelPosition,
horizontalAlign,
verticalAlign,
resolvedTextAlign,
emptyMessage: 'No attributes configured.',
errorMessage: error ? String(error) : undefined
};
};
|