Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
69 changes: 52 additions & 17 deletions nodes/widgets/ui_chart.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,59 @@ module.exports = function (RED) {
config.stackSeries = false
}

// the editor hides the y property for JSON series and histograms, so any value left in it must be ignored
const yFromMsg = config.yAxisPropertyType === 'msg' && config.categoryType !== 'json' && config.chartType !== 'histogram'

function getConfiguredY (msg) {
try {
return RED.util.evaluateNodeProperty(config.yAxisProperty, 'msg', node, msg)
} catch (err) {
// Node-RED throws when an intermediate property in the path is missing.
if (!(err instanceof TypeError)) {
throw err
}
}
}

function isDataMsg (msg) {
// An empty payload array clears the chart regardless of the configured Y property.
if (Array.isArray(msg.payload) && !msg.payload.length) {
return true
}

return yFromMsg
? getConfiguredY(msg) !== undefined
: msg.payload !== undefined
}

const evts = {
// beforeSend will run before messages are sent client-side, as well as before sending on within Node-RED
// here, we use it to pre-process chart data to format it ready for plotting
beforeSend: function (msg) {
const updates = msg.ui_update
if (updates) {
if (typeof updates.chartOptions !== 'undefined') {
// merge chart options specified here in with any others previously set
const currentOptions = statestore.getProperty(node.id, 'chartOptions') ?? {}
// Deep merge new options in with old
const mergedOptions = deepMerge(currentOptions, updates.chartOptions)
statestore.set(group.getBase(), node, msg, 'chartOptions', mergedOptions)
// pass the full set to the clients so they don't need to do the merge
msg.ui_update.chartOptions = mergedOptions
}
}

if (!isDataMsg(msg)) {
msg._datapoint = null
return msg
}

// when y is taken from a msg property, a single value takes y from that property, regardless of
// what (or whether) msg.payload holds (an object payload still supplies x and the series). This is
// resolved here, before addToChart, which just adds the y it is given to the chart
const p = msg.payload
const msgY = yFromMsg ? getConfiguredY(msg) : undefined
const single = yFromMsg && typeof p !== 'object' ? msgY : p

let series = RED.util.evaluateNodeProperty(config.category, config.categoryType, node, msg)
// if receiving a object payload, the series could be a within the payload
Expand All @@ -149,26 +197,13 @@ module.exports = function (RED) {
const points = []
series.forEach((s) => {
if (hasProperty(p, s)) {
const datapoint = addToChart(p, s)
const datapoint = addToChart(single, s)
points.push(datapoint)
}
})
msg._datapoint = points
} else {
msg._datapoint = addToChart(p, series)
}
}

const updates = msg.ui_update
if (updates) {
if (typeof updates.chartOptions !== 'undefined') {
// merge chart options specified here in with any others previously set
const currentOptions = statestore.getProperty(node.id, 'chartOptions') ?? {}
// Deep merge new options in with old
const mergedOptions = deepMerge(currentOptions, updates.chartOptions)
statestore.set(group.getBase(), node, msg, 'chartOptions', mergedOptions)
// pass the full set to the clients so they don't need to do the merge
msg.ui_update.chartOptions = mergedOptions
msg._datapoint = addToChart(single, series)
}
}

Expand Down Expand Up @@ -233,8 +268,8 @@ module.exports = function (RED) {
if (!datastore.has(node.id)) {
datastore.save(base, node, [])
}
// To prevent ui_update messages from deleting old data, skip this section if no msg.payload present
if (typeof msg.payload !== 'undefined') {
// To prevent ui_update messages from deleting old data, skip this section if the msg carries no data
if (isDataMsg(msg)) {
if (Array.isArray(msg.payload) && !msg.payload.length) {
// clear history
datastore.save(base, node, [])
Expand Down
191 changes: 191 additions & 0 deletions test/nodes/widgets/ui_chart.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
const { EventEmitter, once } = require('node:events')

const helper = require('node-red-node-test-helper')
const should = require('should') // eslint-disable-line no-unused-vars

const datastore = require('../../../nodes/store/data.js')
const { testData1 } = require('../fixtures/index.js')
const testFlow1 = testData1.flows
const nodeImports = testData1.getImports(null, ['ui_chart'])

helper.init(require.resolve('node-red'))

describe('ui-chart node', function () {
beforeEach(function (done) {
helper.startServer(done)
})

afterEach(function (done) {
helper.unload()
helper.stopServer(done)
})

function chartFlow (overrides) {
return [
{
id: 'node-ui-chart',
type: 'ui-chart',
z: 'tab-id',
group: 'config-ui-group',
name: '',
label: 'chart',
order: 0,
chartType: 'line',
category: 'topic',
categoryType: 'msg',
xAxisProperty: '',
xAxisPropertyType: 'timestamp',
xAxisType: 'time',
yAxisProperty: 'payload',
yAxisPropertyType: 'msg',
action: 'append',
width: 4,
height: 4,
wires: [],
...overrides
},
...testFlow1
]
}

async function datapointFor (overrides, msg) {
const flow = chartFlow(overrides)
await helper.load(nodeImports, flow)
const chart = helper.getNode('node-ui-chart')
const base = helper.getNode('config-ui-base')
const widget = base.ui.widgets.get('node-ui-chart')
const out = widget.hooks.beforeSend({ ...msg })
should(chart).be.an.Object()
return out._datapoint
}

it('uses msg.payload for a numeric payload by default', async function () {
const dp = await datapointFor({}, { topic: 'a', payload: 7, value: 3 })
dp.y.should.equal(7)
})

it('uses the configured msg property for the y value when payload is a number', async function () {
const dp = await datapointFor({ yAxisProperty: 'value', yAxisPropertyType: 'msg' }, { topic: 'a', payload: 7, value: 3 })
dp.y.should.equal(3)
})

it('uses the configured msg property for the y value when payload is a string', async function () {
const dp = await datapointFor({ yAxisProperty: 'value', yAxisPropertyType: 'msg' }, { topic: 'a', payload: '7', value: 3 })
dp.y.should.equal(3)
})

it('uses the configured msg property for the y value when msg.payload is not set', async function () {
const dp = await datapointFor({ yAxisProperty: 'value', yAxisPropertyType: 'msg' }, { topic: 'a', value: 3 })
dp.y.should.equal(3)
})

it('uses the configured msg property for the y value when payload is an object', async function () {
const dp = await datapointFor({ yAxisProperty: 'value', yAxisPropertyType: 'msg', xAxisProperty: 'ts', xAxisPropertyType: 'property' }, { topic: 'a', payload: { y: 7, ts: 123 }, value: 3 })
dp.y.should.equal(3)
dp.x.should.equal(123)
})

it('stores a point in the datastore when y is a msg property and msg.payload is not set', async function () {
const flow = chartFlow({ yAxisProperty: 'value', yAxisPropertyType: 'msg' })
await helper.load(nodeImports, flow)
const base = helper.getNode('config-ui-base')
const widget = base.ui.widgets.get('node-ui-chart')
datastore.save(base, helper.getNode('node-ui-chart'), [])
const msg = widget.hooks.beforeSend({ topic: 'a', value: 3 })
await new Promise((resolve) => widget.hooks.onInput(msg, resolve, () => {}))
const stored = datastore.get('node-ui-chart')
stored.should.have.length(1)
stored[0]._datapoint.y.should.equal(3)
})

it('does not store a point for a ui_update msg without payload', async function () {
const flow = chartFlow({ yAxisProperty: 'value', yAxisPropertyType: 'msg' })
await helper.load(nodeImports, flow)
const base = helper.getNode('config-ui-base')
const widget = base.ui.widgets.get('node-ui-chart')
datastore.save(base, helper.getNode('node-ui-chart'), [])
const msg = widget.hooks.beforeSend({ topic: 'a', ui_update: { chartOptions: {} } })
await new Promise((resolve) => widget.hooks.onInput(msg, resolve, () => {}))
datastore.get('node-ui-chart').should.have.length(0)
})

it('stores a point for a msg carrying both a ui_update and a value in the y property', async function () {
const flow = chartFlow({ yAxisProperty: 'value', yAxisPropertyType: 'msg' })
await helper.load(nodeImports, flow)
const base = helper.getNode('config-ui-base')
const widget = base.ui.widgets.get('node-ui-chart')
datastore.save(base, helper.getNode('node-ui-chart'), [])
const msg = widget.hooks.beforeSend({ topic: 'a', value: 3, ui_update: { chartOptions: {} } })
await new Promise((resolve) => widget.hooks.onInput(msg, resolve, () => {}))
const stored = datastore.get('node-ui-chart')
stored.should.have.length(1)
stored[0]._datapoint.y.should.equal(3)
})

it('emits a chart options update when the parent of the configured y property is missing', async function () {
const flow = chartFlow({ yAxisProperty: 'value.y', yAxisPropertyType: 'msg' })
await helper.load(nodeImports, flow)
const chart = helper.getNode('node-ui-chart')
const base = helper.getNode('config-ui-base')
const emitter = new EventEmitter()
base.uiShared.connections['chart-test'] = { id: 'chart-test', emit: emitter.emit.bind(emitter) }
const history = [{ _datapoint: { x: 1, y: 3, category: 'a' } }]
datastore.save(base, chart, history)

const update = { chartOptions: { title: { text: 'Updated' } } }
const received = once(emitter, 'msg-input:' + chart.id)
chart.receive({ ui_update: update })
const [msg] = await received
msg.ui_update.should.deepEqual(update)
should(msg._datapoint).equal(null)
datastore.get(chart.id).should.deepEqual(history)
})

it('does not store a point when y is a msg property that is missing and msg.payload is not a clear request', async function () {
const flow = chartFlow({ yAxisProperty: 'value', yAxisPropertyType: 'msg' })
await helper.load(nodeImports, flow)
const base = helper.getNode('config-ui-base')
const widget = base.ui.widgets.get('node-ui-chart')
datastore.save(base, helper.getNode('node-ui-chart'), [])
for (const payload of [[{ y: 7 }], 7]) {
const msg = widget.hooks.beforeSend({ topic: 'a', payload })
await new Promise((resolve) => widget.hooks.onInput(msg, resolve, () => {}))
datastore.get('node-ui-chart').should.have.length(0)
should(msg._datapoint).equal(null)
}
})

it('plots one point per JSON series regardless of the configured y msg property', async function () {
const flow = chartFlow({ category: '["sin","cos"]', categoryType: 'json', yAxisProperty: 'payload.value', yAxisPropertyType: 'msg' })
await helper.load(nodeImports, flow)
const base = helper.getNode('config-ui-base')
const widget = base.ui.widgets.get('node-ui-chart')
datastore.save(base, helper.getNode('node-ui-chart'), [])
const msg = widget.hooks.beforeSend({ payload: { sin: 5, cos: 8 } })
await new Promise((resolve) => widget.hooks.onInput(msg, resolve, () => {}))
msg._datapoint.map((d) => [d.category, d.y]).should.deepEqual([['sin', 5], ['cos', 8]])
datastore.get('node-ui-chart').should.have.length(1)
})

it('plots a histogram value regardless of the configured y msg property', async function () {
const dp = await datapointFor({ chartType: 'histogram', xAxisType: 'bins', yAxisProperty: 'value', yAxisPropertyType: 'msg' }, { topic: 'a', payload: 7 })
dp.y.should.equal(7)
})

it('clears chart history with an empty payload array when y is a different msg property', async function () {
const flow = chartFlow({ yAxisProperty: 'value', yAxisPropertyType: 'msg' })
await helper.load(nodeImports, flow)
const chart = helper.getNode('node-ui-chart')
const base = helper.getNode('config-ui-base')
const emitter = new EventEmitter()
base.uiShared.connections['chart-test'] = { id: 'chart-test', emit: emitter.emit.bind(emitter) }
const history = [{ _datapoint: { x: 1, y: 3, category: 'a' } }]
datastore.save(base, chart, history)

const received = once(emitter, 'msg-input:' + chart.id)
chart.receive({ payload: [] })
const [msg] = await received
datastore.get(chart.id).should.have.length(0)
should(msg._datapoint).deepEqual([])
})
})
11 changes: 8 additions & 3 deletions ui/src/widgets/ui-chart/UIChart.vue
Original file line number Diff line number Diff line change
Expand Up @@ -415,9 +415,14 @@
}
},
onMsgInput (msg) {
// The server marks messages that carry no chart data. Dynamic updates are handled separately.
if (msg._datapoint === null) {
return
}
// ignore if payload is empty and msg is not an array (on loading it can be an array)
// ui_update messages are handled by OnDynamicProperties
if (msg.payload !== undefined || Array.isArray(msg)) {
// a msg without payload is still data when the server computed a y value for it (y set to a msg property)
if (msg.payload !== undefined || Array.isArray(msg) || (msg._datapoint && msg._datapoint.y !== undefined)) {
if (Array.isArray(msg.payload) && !msg.payload.length) {
// clear the chart if msg.payload = [] is received
this.clearChart()
Expand Down Expand Up @@ -533,8 +538,8 @@
this.addPoints(p, d, label, options)
}
})
} else if (payload !== null && payload !== undefined) {
// we have a single payload value and should append it to the chart
} else if ((payload !== null && payload !== undefined) || (payload === undefined && msg._datapoint && !Array.isArray(msg._datapoint) && msg._datapoint.y !== undefined)) {
// we have a single payload value (or a y value taken from a msg property) and should append it to the chart
if (Array.isArray(msg._datapoint)) {
// single message has multiple datapoints to render (e.g. when Series is set to JSON)
msg._datapoint.forEach((d) => {
Expand Down Expand Up @@ -754,10 +759,10 @@
updateYAxisLimits (options) {
if (this.hasData && this.props.xAxisType !== 'radial') {
if (!Object.hasOwn(this.props, 'ymin') || this.props.ymin === '' || typeof this.props.ymin === 'undefined') {
options.yAxis[0].min = axisHelper.getAxisMin // set sensible y-limits

Check warning on line 762 in ui/src/widgets/ui-chart/UIChart.vue

View workflow job for this annotation

GitHub Actions / build / Build on 24

Caution: `axisHelper` also has a named export `getAxisMin`. Check if you meant to write `import {getAxisMin} from './helpers/axis.helper'` instead
}
if (!Object.hasOwn(this.props, 'ymax') || this.props.ymax === '' || typeof this.props.ymax === 'undefined') {
options.yAxis[0].max = axisHelper.getAxisMax // set sensible y-limits

Check warning on line 765 in ui/src/widgets/ui-chart/UIChart.vue

View workflow job for this annotation

GitHub Actions / build / Build on 24

Caution: `axisHelper` also has a named export `getAxisMax`. Check if you meant to write `import {getAxisMax} from './helpers/axis.helper'` instead
}
}
},
Expand Down
Loading