import React, { memo, useContext, useEffect, useState } from 'react'; import { Handle, Position, useNodeConnections, type NodeProps } from '@xyflow/react'; import { ListItemIcon, ListItemText, Menu, MenuItem } from '@mui/material'; import { ContentCopy as IconDuplicate, Delete as IconDelete, MoreVert as IconMore, PushPin as IconPinned, PushPinOutlined as IconPin, Settings as IconSettings, StickyNote2 as IconNote, Adjust as IconBreakpoint, LockOutlined as IconEnforce, ZoomIn as IconInside, } from '@mui/icons-material'; import { I18n } from '@iobroker/gui-components'; import { formatClock, formatTime, getBlockDef, getInputs, getOutputs, parseTime, resolvePinType, type FbBlock, type FbBlockDef, type FbBlockMetrics, type FbPin, type FbSignalType, type FbValue, } from '@fb-core'; import BlockIcon from './BlockIcon'; import { CATEGORY_COLORS, TYPE_COLORS, type BlockNode as BlockNodeType } from './convert'; import { LiveValue, formatLive } from './online'; import { FbViewContext } from './ViewContext'; /** Head bar with the instance name, and the line with the type under it */ const BAR_HEIGHT = 28; const TITLE_HEIGHT = 24; /** How a block is drawn - the automatic layout needs it to put the pins level */ export const BLOCK_METRICS: FbBlockMetrics = { header: BAR_HEIGHT + TITLE_HEIGHT, detail: 30, pin: 24, frame: 8 }; export const PIN_HEIGHT = BLOCK_METRICS.pin; /** The value an input that is not connected gets, as text */ export function formatValue(pin: FbPin, block: FbBlock): string { return formatShown(block.params?.[pin.id] ?? pin.default, pin.type, pin.clock); } /** `clock`: a TIME that is a time of day, shown as `08:30` */ function formatShown(value: FbValue | undefined, type: FbSignalType | 'ANY', clock?: boolean): string { if (value === undefined || value === null) { return ''; } if (type === 'TIME') { if (typeof value !== 'number') { return String(value); } return clock ? formatClock(value) : formatTime(value); } return String(value); } /** An offset of ASTRO in minutes, as `+30'` - nothing for 0 */ function formatOffset(value: FbValue | undefined): string { const minutes = Math.round(Number(value)) || 0; return minutes ? `${minutes > 0 ? '+' : '−'}${Math.abs(minutes)}'` : ''; } /** The first line of the code of a JS block that is not empty and no comment */ function firstCodeLine(code: FbValue | undefined): string { const lines = String(code ?? '') .split('\n') .map(line => line.trim()); return lines.find(line => line && !line.startsWith('//')) || lines.find(line => line) || ''; } /** A value typed in, in the type it is for - `null` if it is none */ export function parseValue(text: string, type: FbSignalType | 'ANY'): FbValue | null { switch (type) { case 'TIME': return parseTime(text); case 'INT': return /^-?\d+$/.test(text.trim()) ? parseInt(text, 10) : null; case 'REAL': return text.trim() !== '' && Number.isFinite(Number(text)) ? Number(text) : null; default: return text; } } /** * A value right in the block: a BOOL switches with a click, anything else is typed in and taken on * Enter or when the field is left. Without `onChange` it can only be read. */ function InlineValue(props: { value: FbValue | undefined; type: FbSignalType | 'ANY'; clock?: boolean; onChange?: (value: FbValue) => void; wide?: boolean; }): React.JSX.Element { const { value, type, onChange } = props; const shown = formatShown(value, type, props.clock); const [text, setText] = useState(shown); useEffect(() => setText(shown), [shown]); if (type === 'BOOL') { const on = value === true || value === 'true'; return ( ); } const className = `fb-inline${props.wide ? ' fb-inline-wide' : ''}${type === 'STRING' ? ' fb-inline-string' : ''}`; if (!onChange) { return {shown}; } const parsed = parseValue(text, type); const commit = (): void => { if (parsed !== null && text !== shown) { onChange(parsed); } else { setText(shown); } }; return ( setText(event.target.value)} onBlur={commit} onKeyDown={event => { if (event.key === 'Enter') { event.currentTarget.blur(); } else if (event.key === 'Escape') { setText(shown); } }} title={parsed === null ? I18n.t(type === 'TIME' ? 'fbd_invalid_time' : 'fbd_invalid_number') : undefined} /> ); } /** Blocks with a line under the type - the same rule as in the automatic layout */ function hasDetail(def: FbBlockDef | undefined): boolean { return !!def?.user || !!def?.params?.length; } /** * A block: a card in the color of its category. The head has the instance name and the actions, the * type follows in color, then what the block is about (state, value, pin, version), then the pins - * inputs on the left with the value of an open input right beside them, outputs on the right. */ function BlockNode({ id, data, selected }: NodeProps): React.JSX.Element { const view = useContext(FbViewContext); const connections = useNodeConnections({ handleType: 'target' }); const [menu, setMenu] = useState(null); const { block } = data; const { actions, debug } = view; const def = getBlockDef(block.type, view.userBlocks); const inputs = getInputs(block, def); const outputs = getOutputs(block, def); const detail = hasDetail(def); const rows = Math.max(inputs.length, outputs.length, 1); const top = BLOCK_METRICS.header + (detail ? BLOCK_METRICS.detail : 0); const connected = new Set(connections.map(connection => connection.targetHandle)); const color = def ? CATEGORY_COLORS[def.category] : '#ef4444'; // the running diagram failed in this block const runtimeError = view.runtimeError?.blockId === id ? view.runtimeError.message : null; const hasError = view.errors.has(id) || !!runtimeError; const breakpoint = debug.breakpoints.has(id); // paused in front of this block const next = debug.at === id; // online: the state the block writes holds another value - somebody else changed it const oid = block.type === 'STATE_OUT' && block.params?.oid ? String(block.params.oid) : ''; const deviates = !!oid && Object.prototype.hasOwnProperty.call(view.deviations, oid); const actual = deviates ? formatLive(view.deviations[oid], 'ANY') : ''; const enforce = block.type === 'STATE_OUT' && block.params?.enforce === true; const setParam = actions ? (param: string, value: FbValue): void => actions.change({ ...block, params: { ...block.params, [param]: value } }) : undefined; const description = def?.user ? def.user.description || def.user.name : def ? I18n.t(`fbd_desc_${block.type}`) : I18n.t('Unknown block type %s', block.type); const title = runtimeError ? I18n.t('fbd_runtime_error', runtimeError) : deviates ? `${I18n.t(enforce ? 'fbd_deviation_enforced' : 'fbd_deviation', actual)}\n\n${description}` : block.comment ? `${block.comment}\n\n${description}` : description; const renderDetail = (): React.JSX.Element => { if (def?.user) { return v{def.user.version}; } if (block.type === 'CONST') { const type = resolvePinType(block, { param: 'type' }, def); return ( setParam('value', value))} /> ); } const text = (): React.JSX.Element => ( setParam('text', value))} /> ); if (block.type === 'LOG') { const level = String(block.params?.level || 'info'); return ( <> {level} {text()} ); } if (block.type === 'NOTIFY') { const category = String(block.params?.category || 'message'); return ( <> {I18n.t(`fbd_option_${category}`)} {text()} ); } if (block.type === 'SENDTO') { const instance = block.params?.instance ? String(block.params.instance) : ''; return ( <> {instance || '?'} {text()} ); } if (block.type === 'SCHEDULE') { return ( setParam('cron', value))} /> ); } if (block.type === 'TIMEWINDOW') { return ( {I18n.t(`fbd_option_${String(block.params?.days || 'all')}`)} ); } if (block.type === 'ASTRO') { const event = (param: string): string => `${I18n.t(`fbd_option_${String(block.params?.[param] || '')}`)}${formatOffset(block.params?.[`${param}Offset`])}`; return ( {event('start')} → {event('end')} ); } if (block.type === 'JS') { const code = String(block.params?.code ?? ''); return ( {firstCodeLine(code)} ); } if (block.type === 'FB_IN' || block.type === 'FB_OUT') { return ( {String(block.params?.pin || '?')}: {String(block.params?.type || 'BOOL')} ); } if (def?.params?.length === 1 && def.params[0].id === 'type') { // a block for every type, like SEL or MUX: the one it works with return {resolvePinType(block, { param: 'type' }, def)}; } const state = block.params?.oid ? String(block.params.oid) : ''; return ( <> {enforce ? ( ) : null} {state || I18n.t('fbd_no_state')} {deviates ? {actual} : null} ); }; const menuAction = (action: () => void) => () => { setMenu(null); action(); }; const pinned = !!block.pinned; const pinTitle = `${I18n.t(pinned ? 'fbd_unpin' : 'fbd_pin')}\n${I18n.t('fbd_pin_hint')}`; return (
{breakpoint || debug.enabled ? ( { event.stopPropagation(); debug.toggleBreakpoint(id); } : undefined } /> ) : null} {block.name} {block.comment ? : null} {actions ? ( <> ) : null}
{def?.user ? def.user.name : block.type} {view.order[id] !== undefined ? {view.order[id]} : null}
{detail ? (
{renderDetail()}
) : null} {Array.from({ length: rows }, (_, i) => { const input = inputs[i]; const output = outputs[i]; return (
{input ? ( <> {input.id} {!connected.has(input.id) ? ( setParam(input.id, value))} /> ) : null} ) : null} {output ? output.id : null}
); })}
{inputs.map((pin, i) => { const y = top + i * PIN_HEIGHT + PIN_HEIGHT / 2; return ( {block.pins?.[pin.id]?.inverted ? (
) : null} ); })} {outputs.map((pin, i) => { const y = top + i * PIN_HEIGHT + PIN_HEIGHT / 2; return ( ); })} {menu && actions ? ( setMenu(null)} onClick={event => event.stopPropagation()} > actions.select(id))}> {I18n.t('fbd_menu_properties')} {def?.user ? ( actions.openInstance(id))}> {I18n.t('fbd_instance_open')} ) : null} {debug.enabled ? ( debug.toggleBreakpoint(id))}> {I18n.t(breakpoint ? 'fbd_debug_breakpoint_remove' : 'fbd_debug_breakpoint_set')} ) : null} actions.pin(id, !pinned))} title={I18n.t('fbd_pin_hint')} > {pinned ? : } {I18n.t(pinned ? 'fbd_unpin' : 'fbd_pin')} actions.duplicate(id))}> {I18n.t('fbd_menu_duplicate')} actions.remove(id))}> {I18n.t('Delete')} ) : null}
); } export default memo(BlockNode);