pict-section-form 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -102,10 +102,58 @@ Raw -> Address (overrides) -> Solver (merges) -> Final Configuration
102
102
  "CustomXAxisID": "x-axis-1",
103
103
  "Tension": 0.4,
104
104
  "PointRadius": 5,
105
- "StackGroup": "stack1"
105
+ "StackGroup": "stack1",
106
+ "ValueLabels": false
106
107
  }
107
108
  ```
108
109
 
110
+ `ValueLabels` turns one dataset's point value labels off (or on, under
111
+ `"Datasets": "OptIn"`); see [Point Value Labels](#point-value-labels).
112
+
113
+ ### Point Value Labels
114
+
115
+ Chart.js shows a point's value only in its hover tooltip. `ChartValueLabels`
116
+ draws every value on the chart instead, which also puts the values in a printed
117
+ chart. No Chart.js plugin is needed.
118
+
119
+ ```json
120
+ "ChartValueLabels": true
121
+ ```
122
+
123
+ or, with options:
124
+
125
+ ```json
126
+ "ChartValueLabels": {
127
+ "Decimals": 1,
128
+ "Position": "top",
129
+ "Color": "Dataset"
130
+ }
131
+ ```
132
+
133
+ | Property | Type | Default | Description |
134
+ |----------|------|---------|-------------|
135
+ | `Enabled` | boolean | `true` | `false` turns the labels off while keeping the rest of the block |
136
+ | `Datasets` | string | `"All"` | `"All"` labels every dataset except those with `ValueLabels: false`; `"OptIn"` labels only datasets with `ValueLabels: true` |
137
+ | `Position` | string | `"top"` | `"top"`, `"bottom"` or `"center"` of the point. Arc charts (pie, doughnut, polar area) always label the centre of each slice, and a negative bar's label goes on its far side |
138
+ | `Decimals` | number | — | Fixed decimal places. Without it the value is shown as is, with floating-point noise trimmed |
139
+ | `Color` | string | chart text colour | Any CSS colour, or `"Dataset"` to draw each label in its series' border colour |
140
+ | `FontSize` | number | `11` | Pixels |
141
+ | `FontWeight` | string | `"normal"` | Any CSS font weight |
142
+ | `Offset` | number | `4` | Pixels between the point marker and its label |
143
+ | `Padding` | number | `2` | Pixels around the text that count toward its box when checking for overlap |
144
+ | `HideOverlaps` | boolean | `true` | When a label would overlap one already placed, move it to the other side of its point, or hide it if that side is taken too. `false` draws every label |
145
+ | `Halo` | boolean | `true` | Draw an outline behind the text so it stays readable over lines and grid. It is light behind dark text and dark behind light text, so it follows the page theme |
146
+ | `HaloColor` | string | from the text colour | Any CSS colour |
147
+ | `HaloWidth` | number | `3` | Pixels |
148
+
149
+ Labels are placed in dataset order and then point order, so list the series
150
+ whose values matter most first: it keeps its labels when series crowd each
151
+ other. A label that would leave the plot area is flipped to the other side of
152
+ its point and kept inside the plot. With `Position: "top"`, the chart reserves
153
+ room above the plot for the highest label, unless the configuration already sets
154
+ `options.layout.padding`. Blank points and datasets hidden from the legend get no
155
+ labels.
156
+
109
157
  ## Examples
110
158
 
111
159
  ### Raw Data Configuration
@@ -196,6 +196,41 @@ module.exports.default_configuration.pict_configuration =
196
196
  ]
197
197
  }
198
198
  },
199
+ "OverviewChart.SugarAndCarbohydrates":
200
+ {
201
+ Name: "Sugar vs Carbohydrates (values on the points; crowded labels move or hide)",
202
+ Hash: "OverviewSugarCarbChart",
203
+ DataType: "Object",
204
+ PictForm:
205
+ {
206
+ Section: "OverviewCharts", Group: "OverviewCharts",
207
+ Row: 2, Width: 12,
208
+ InputType: "Chart",
209
+ ChartType: "line",
210
+ ChartHeight: 320,
211
+ ChartValueLabels: { Decimals: 1, Color: "Dataset" },
212
+ ChartLabelsSolver: `objectkeystoarray(aggregationhistogrambyobject(FruitGrid, "name", "nutritions.sugar"))`,
213
+ ChartDatasetsSolvers:
214
+ [
215
+ {
216
+ Label: 'Carbohydrates (g)',
217
+ DataSolver: `objectvaluestoarray(aggregationhistogrambyobject(FruitGrid, "name", "nutritions.carbohydrates"))`,
218
+ DatasetOptions: { borderColor: '#1971C2', backgroundColor: '#1971C2' }
219
+ },
220
+ {
221
+ Label: 'Sugar (g)',
222
+ DataSolver: `objectvaluestoarray(aggregationhistogrambyobject(FruitGrid, "name", "nutritions.sugar"))`,
223
+ DatasetOptions: { borderColor: '#E8590C', backgroundColor: '#E8590C' }
224
+ },
225
+ {
226
+ Label: 'Protein (g, unlabelled)',
227
+ DataSolver: `objectvaluestoarray(aggregationhistogrambyobject(FruitGrid, "name", "nutritions.protein"))`,
228
+ ValueLabels: false,
229
+ DatasetOptions: { borderColor: '#868E96', backgroundColor: '#868E96', borderDash: [ 4, 4 ] }
230
+ }
231
+ ]
232
+ }
233
+ },
199
234
  },
200
235
 
201
236
  // ════════════════════════════════════════════════════════════
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pict-section-form",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "description": "Pict dynamic forms",
5
5
  "main": "source/Pict-Section-Form.js",
6
6
  "directories": {
@@ -345,6 +345,324 @@ class CustomInputHandler extends libPictSectionInputExtension
345
345
  return tmpLegend;
346
346
  }
347
347
 
348
+ /**
349
+ * Resolve the ChartValueLabels configuration for an input, filled out with
350
+ * defaults. Returns null when values are not drawn on the chart, in which
351
+ * case they show only in the hover tooltip.
352
+ *
353
+ * @param {Object} pInput - The PictForm input object.
354
+ * @return {Object|null}
355
+ */
356
+ resolveChartValueLabelConfiguration(pInput)
357
+ {
358
+ const tmpPictform = (pInput && pInput.PictForm) || {};
359
+ let tmpValueLabels = tmpPictform.ChartValueLabels;
360
+ if (tmpValueLabels === true)
361
+ {
362
+ tmpValueLabels = {};
363
+ }
364
+ if (!tmpValueLabels || (typeof (tmpValueLabels) !== 'object') || (tmpValueLabels.Enabled === false))
365
+ {
366
+ return null;
367
+ }
368
+ const tmpConfiguration = Object.assign(
369
+ {
370
+ Datasets: 'All',
371
+ Position: 'top',
372
+ Offset: 4,
373
+ Padding: 2,
374
+ FontSize: 11,
375
+ FontWeight: 'normal',
376
+ HideOverlaps: true,
377
+ }, tmpValueLabels);
378
+ if ([ 'top', 'bottom', 'center' ].indexOf(tmpConfiguration.Position) < 0)
379
+ {
380
+ tmpConfiguration.Position = 'top';
381
+ }
382
+ const fNumberOr = (pValue, pDefault) =>
383
+ {
384
+ const tmpNumber = parseFloat(pValue);
385
+ return (isFinite(tmpNumber) && (tmpNumber >= 0)) ? tmpNumber : pDefault;
386
+ };
387
+ tmpConfiguration.Offset = fNumberOr(tmpConfiguration.Offset, 4);
388
+ tmpConfiguration.Padding = fNumberOr(tmpConfiguration.Padding, 2);
389
+ tmpConfiguration.FontSize = fNumberOr(tmpConfiguration.FontSize, 11) || 11;
390
+ return tmpConfiguration;
391
+ }
392
+
393
+ /**
394
+ * Build the Chart.js inline plugin that draws each point's value on the chart.
395
+ *
396
+ * @param {Object} pConfiguration - From resolveChartValueLabelConfiguration.
397
+ * @return {Object} A Chart.js plugin.
398
+ */
399
+ createChartValueLabelPlugin(pConfiguration)
400
+ {
401
+ return (
402
+ {
403
+ id: 'pictValueLabels',
404
+ afterDatasetsDraw: (pChart) =>
405
+ {
406
+ this.drawChartValueLabels(pChart, pConfiguration);
407
+ },
408
+ });
409
+ }
410
+
411
+ /**
412
+ * Format a value for its label: blanks and non-numbers draw nothing, and
413
+ * floating-point noise (0.30000000000000004) is trimmed unless Decimals fixes
414
+ * the places.
415
+ *
416
+ * @param {any} pValue - The parsed data value.
417
+ * @param {Object} pConfiguration - From resolveChartValueLabelConfiguration.
418
+ * @return {string|null} The label text, or null for no label.
419
+ */
420
+ _formatChartValueLabel(pValue, pConfiguration)
421
+ {
422
+ if ((pValue === null) || (typeof (pValue) === 'undefined') || (pValue === ''))
423
+ {
424
+ return null;
425
+ }
426
+ const tmpNumber = Number(pValue);
427
+ if (!isFinite(tmpNumber))
428
+ {
429
+ return null;
430
+ }
431
+ const tmpDecimals = parseInt(pConfiguration.Decimals, 10);
432
+ if (isFinite(tmpDecimals) && (tmpDecimals >= 0))
433
+ {
434
+ return tmpNumber.toFixed(Math.min(tmpDecimals, 20));
435
+ }
436
+ return String(parseFloat(tmpNumber.toPrecision(12)));
437
+ }
438
+
439
+ /**
440
+ * Work out every candidate value label for a drawn chart: its text, colour and
441
+ * box. A box that would leave the plot area is flipped to the other side of
442
+ * its point, then clamped inside.
443
+ *
444
+ * @param {Object} pChart - The Chart.js instance.
445
+ * @param {Object} pConfiguration - From resolveChartValueLabelConfiguration.
446
+ * @param {(pText: string) => number} fMeasureText - Returns the drawn width of a label's text.
447
+ * @return {Array<{ Text: string, Color: string, X: number, Y: number, Left: number, Top: number, Width: number, Height: number, DatasetIndex: number, Index: number }>}
448
+ */
449
+ _collectChartValueLabels(pChart, pConfiguration, fMeasureText)
450
+ {
451
+ const tmpLabels = [];
452
+ const tmpArea = pChart && pChart.chartArea;
453
+ const tmpDatasets = (pChart && pChart.data && pChart.data.datasets) || [];
454
+ if (!tmpArea)
455
+ {
456
+ return tmpLabels;
457
+ }
458
+ const tmpAllDatasets = (pConfiguration.Datasets !== 'OptIn');
459
+ const tmpHeight = pConfiguration.FontSize + (2 * pConfiguration.Padding);
460
+ for (let i = 0; i < tmpDatasets.length; i++)
461
+ {
462
+ const tmpDataset = tmpDatasets[i];
463
+ if (!tmpDataset)
464
+ {
465
+ continue;
466
+ }
467
+ const tmpIncluded = (tmpDataset.pictValueLabels === true) || (tmpAllDatasets && (tmpDataset.pictValueLabels !== false));
468
+ if (!tmpIncluded)
469
+ {
470
+ continue;
471
+ }
472
+ if ((typeof (pChart.isDatasetVisible) === 'function') && !pChart.isDatasetVisible(i))
473
+ {
474
+ continue;
475
+ }
476
+ const tmpMeta = pChart.getDatasetMeta(i);
477
+ if (!tmpMeta || !Array.isArray(tmpMeta.data))
478
+ {
479
+ continue;
480
+ }
481
+ const tmpValueAxis = (tmpMeta.vScale && tmpMeta.vScale.axis) || 'y';
482
+ for (let j = 0; j < tmpMeta.data.length; j++)
483
+ {
484
+ const tmpElement = tmpMeta.data[j];
485
+ if (!tmpElement || tmpElement.skip)
486
+ {
487
+ continue;
488
+ }
489
+ let tmpValue = (tmpMeta.controller && (typeof (tmpMeta.controller.getParsed) === 'function')) ? tmpMeta.controller.getParsed(j) : tmpDataset.data[j];
490
+ if ((typeof (tmpValue) === 'object') && (tmpValue !== null))
491
+ {
492
+ tmpValue = (tmpValueAxis in tmpValue) ? tmpValue[tmpValueAxis] : tmpValue.y;
493
+ }
494
+ const tmpText = this._formatChartValueLabel(tmpValue, pConfiguration);
495
+ if (tmpText === null)
496
+ {
497
+ continue;
498
+ }
499
+ const tmpPosition = (typeof (tmpElement.tooltipPosition) === 'function') ? tmpElement.tooltipPosition(false) : tmpElement;
500
+ if (!isFinite(tmpPosition.x) || !isFinite(tmpPosition.y))
501
+ {
502
+ continue;
503
+ }
504
+ const tmpWidth = fMeasureText(tmpText) + (2 * pConfiguration.Padding);
505
+ const tmpRadius = (tmpElement.options && isFinite(tmpElement.options.radius)) ? Number(tmpElement.options.radius) : 0;
506
+ const tmpGap = tmpRadius + pConfiguration.Offset;
507
+ // Arcs (pie, doughnut, polar area) label their centroid
508
+ let tmpPlacement = (typeof (tmpElement.outerRadius) === 'number') ? 'center' : pConfiguration.Position;
509
+ // A bar below its base reads from its far end, so its label goes underneath
510
+ if ((tmpPlacement !== 'center') && ('base' in tmpElement) && (Number(tmpValue) < 0))
511
+ {
512
+ tmpPlacement = (tmpPlacement === 'top') ? 'bottom' : 'top';
513
+ }
514
+ const tmpAboveTop = tmpPosition.y - tmpGap - tmpHeight;
515
+ const tmpBelowTop = tmpPosition.y + tmpGap;
516
+ const fClampTop = (pTop) => Math.max(tmpArea.top, Math.min(pTop, tmpArea.bottom - tmpHeight));
517
+ let tmpTop = tmpPosition.y - (tmpHeight / 2);
518
+ // The other side of the point, tried when the first choice collides with a kept label
519
+ let tmpAlternateTop = null;
520
+ if (tmpPlacement === 'top')
521
+ {
522
+ const tmpFits = (tmpAboveTop >= tmpArea.top);
523
+ tmpTop = tmpFits ? tmpAboveTop : tmpBelowTop;
524
+ tmpAlternateTop = tmpFits ? fClampTop(tmpBelowTop) : null;
525
+ }
526
+ else if (tmpPlacement === 'bottom')
527
+ {
528
+ const tmpFits = ((tmpBelowTop + tmpHeight) <= tmpArea.bottom);
529
+ tmpTop = tmpFits ? tmpBelowTop : tmpAboveTop;
530
+ tmpAlternateTop = tmpFits ? fClampTop(tmpAboveTop) : null;
531
+ }
532
+ tmpTop = fClampTop(tmpTop);
533
+ const tmpLeft = Math.max(tmpArea.left, Math.min(tmpPosition.x - (tmpWidth / 2), tmpArea.right - tmpWidth));
534
+ let tmpColor = pConfiguration.Color || (pChart.options && pChart.options.color) || '#666';
535
+ if (pConfiguration.Color === 'Dataset')
536
+ {
537
+ tmpColor = (tmpElement.options && tmpElement.options.borderColor) || tmpDataset.borderColor || (pChart.options && pChart.options.color) || '#666';
538
+ }
539
+ tmpLabels.push(
540
+ {
541
+ Text: tmpText,
542
+ Color: tmpColor,
543
+ X: tmpLeft + (tmpWidth / 2),
544
+ Y: tmpTop + (tmpHeight / 2),
545
+ Left: tmpLeft,
546
+ Top: tmpTop,
547
+ Width: tmpWidth,
548
+ Height: tmpHeight,
549
+ AlternateTop: tmpAlternateTop,
550
+ DatasetIndex: i,
551
+ Index: j,
552
+ });
553
+ }
554
+ }
555
+ return tmpLabels;
556
+ }
557
+
558
+ /**
559
+ * Keep the labels that fit. A label that would overlap one already kept moves
560
+ * to the other side of its point if that is clear, and is hidden otherwise.
561
+ * Earlier datasets win, then earlier points, so the series listed first keeps
562
+ * its values when series crowd each other.
563
+ *
564
+ * @param {Array<Object>} pLabels - From _collectChartValueLabels.
565
+ * @param {boolean} pHideOverlaps - False keeps every label where it was first placed.
566
+ * @return {Array<Object>} The labels to draw.
567
+ */
568
+ _layoutChartValueLabels(pLabels, pHideOverlaps)
569
+ {
570
+ if (!pHideOverlaps)
571
+ {
572
+ return pLabels;
573
+ }
574
+ const tmpKept = [];
575
+ const fIsClear = (pLeft, pTop, pWidth, pHeight) =>
576
+ {
577
+ for (let j = 0; j < tmpKept.length; j++)
578
+ {
579
+ const tmpOther = tmpKept[j];
580
+ if ((pLeft < tmpOther.Left + tmpOther.Width) && (tmpOther.Left < pLeft + pWidth)
581
+ && (pTop < tmpOther.Top + tmpOther.Height) && (tmpOther.Top < pTop + pHeight))
582
+ {
583
+ return false;
584
+ }
585
+ }
586
+ return true;
587
+ };
588
+ for (let i = 0; i < pLabels.length; i++)
589
+ {
590
+ const tmpLabel = pLabels[i];
591
+ if (fIsClear(tmpLabel.Left, tmpLabel.Top, tmpLabel.Width, tmpLabel.Height))
592
+ {
593
+ tmpKept.push(tmpLabel);
594
+ }
595
+ else if ((typeof (tmpLabel.AlternateTop) === 'number') && fIsClear(tmpLabel.Left, tmpLabel.AlternateTop, tmpLabel.Width, tmpLabel.Height))
596
+ {
597
+ tmpKept.push(Object.assign({}, tmpLabel, { Top: tmpLabel.AlternateTop, Y: tmpLabel.AlternateTop + (tmpLabel.Height / 2), AlternateTop: null }));
598
+ }
599
+ }
600
+ return tmpKept;
601
+ }
602
+
603
+ /**
604
+ * The halo drawn behind label text so it stays readable over grid lines and
605
+ * other series: dark behind light text, light behind dark text.
606
+ *
607
+ * @param {string} pTextColor - The chart's text colour.
608
+ * @return {string} The halo colour.
609
+ */
610
+ _chartValueLabelHaloColor(pTextColor)
611
+ {
612
+ const tmpMatch = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(pTextColor || '');
613
+ if (tmpMatch)
614
+ {
615
+ const tmpLuminance = ((0.299 * Number(tmpMatch[1])) + (0.587 * Number(tmpMatch[2])) + (0.114 * Number(tmpMatch[3]))) / 255;
616
+ if (tmpLuminance > 0.5)
617
+ {
618
+ return 'rgba(0, 0, 0, 0.75)';
619
+ }
620
+ }
621
+ return 'rgba(255, 255, 255, 0.85)';
622
+ }
623
+
624
+ /**
625
+ * Draw each point's value on a chart's canvas, after its datasets.
626
+ *
627
+ * @param {Object} pChart - The Chart.js instance.
628
+ * @param {Object} pConfiguration - From resolveChartValueLabelConfiguration.
629
+ * @return {number} How many labels were drawn.
630
+ */
631
+ drawChartValueLabels(pChart, pConfiguration)
632
+ {
633
+ const tmpContext = pChart && pChart.ctx;
634
+ if (!tmpContext || !pChart.chartArea)
635
+ {
636
+ return 0;
637
+ }
638
+ const tmpFamily = (pChart.options && pChart.options.font && pChart.options.font.family) || 'sans-serif';
639
+ tmpContext.save();
640
+ tmpContext.font = `${pConfiguration.FontWeight} ${pConfiguration.FontSize}px ${tmpFamily}`;
641
+ const tmpLabels = this._layoutChartValueLabels(
642
+ this._collectChartValueLabels(pChart, pConfiguration, (pText) => tmpContext.measureText(pText).width),
643
+ pConfiguration.HideOverlaps !== false);
644
+ tmpContext.textAlign = 'center';
645
+ tmpContext.textBaseline = 'middle';
646
+ const tmpHaloWidth = parseFloat(pConfiguration.HaloWidth);
647
+ if (pConfiguration.Halo !== false)
648
+ {
649
+ tmpContext.lineJoin = 'round';
650
+ tmpContext.lineWidth = (isFinite(tmpHaloWidth) && (tmpHaloWidth > 0)) ? tmpHaloWidth : 3;
651
+ tmpContext.strokeStyle = pConfiguration.HaloColor || this._chartValueLabelHaloColor(pChart.options && pChart.options.color);
652
+ }
653
+ for (let i = 0; i < tmpLabels.length; i++)
654
+ {
655
+ if (pConfiguration.Halo !== false)
656
+ {
657
+ tmpContext.strokeText(tmpLabels[i].Text, tmpLabels[i].X, tmpLabels[i].Y);
658
+ }
659
+ tmpContext.fillStyle = tmpLabels[i].Color;
660
+ tmpContext.fillText(tmpLabels[i].Text, tmpLabels[i].X, tmpLabels[i].Y);
661
+ }
662
+ tmpContext.restore();
663
+ return tmpLabels.length;
664
+ }
665
+
348
666
  /**
349
667
  * Resolve the text and grid colours a chart should draw with from the page
350
668
  * around its canvas, so the canvas follows the host's light or dark theme the
@@ -932,6 +1250,11 @@ class CustomInputHandler extends libPictSectionInputExtension
932
1250
  tmpDataObject.pictLegendGroup = tmpCurrentSolverExpression.LegendGroup;
933
1251
  }
934
1252
 
1253
+ if (typeof (tmpCurrentSolverExpression.ValueLabels) === 'boolean')
1254
+ {
1255
+ tmpDataObject.pictValueLabels = tmpCurrentSolverExpression.ValueLabels;
1256
+ }
1257
+
935
1258
  if (tmpParsingConfiguration.ObjectType === 'array')
936
1259
  {
937
1260
  if (Array.isArray(tmpSolvedDataSet))
@@ -1064,6 +1387,26 @@ class CustomInputHandler extends libPictSectionInputExtension
1064
1387
  tmpChartConfiguration.options.plugins.legend = Object.assign({}, tmpChartConfiguration.options.plugins.legend, { display: false });
1065
1388
  }
1066
1389
 
1390
+ const tmpValueLabelConfiguration = this.resolveChartValueLabelConfiguration(pInput);
1391
+ if (tmpValueLabelConfiguration)
1392
+ {
1393
+ if (!Array.isArray(tmpChartConfiguration.plugins))
1394
+ {
1395
+ tmpChartConfiguration.plugins = [];
1396
+ }
1397
+ tmpChartConfiguration.plugins.push(this.createChartValueLabelPlugin(tmpValueLabelConfiguration));
1398
+ // Room above the plot for the topmost point's label, so it does not have to flip below its point
1399
+ if ((tmpValueLabelConfiguration.Position === 'top') && (typeof (tmpChartConfiguration.options?.layout?.padding) === 'undefined'))
1400
+ {
1401
+ if (typeof (tmpChartConfiguration.options) !== 'object' || tmpChartConfiguration.options === null)
1402
+ {
1403
+ tmpChartConfiguration.options = {};
1404
+ }
1405
+ tmpChartConfiguration.options.layout = Object.assign({}, tmpChartConfiguration.options.layout,
1406
+ { padding: { top: tmpValueLabelConfiguration.FontSize + tmpValueLabelConfiguration.Offset + (2 * tmpValueLabelConfiguration.Padding) } });
1407
+ }
1408
+ }
1409
+
1067
1410
  const tmpChartHeight = parseFloat(tmpPictform.ChartHeight);
1068
1411
  if (isFinite(tmpChartHeight) && (tmpChartHeight > 0))
1069
1412
  {