pict-section-form 1.4.2 → 1.4.4

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,60 @@ 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
+ A dataset in `ChartDatasetsRaw` or at `ChartDatasetsAddress` takes the same
113
+ `ValueLabels` key, alongside its Chart.js properties.
114
+
115
+ ### Point Value Labels
116
+
117
+ Chart.js shows a point's value only in its hover tooltip. `ChartValueLabels`
118
+ draws every value on the chart instead, which also puts the values in a printed
119
+ chart. No Chart.js plugin is needed.
120
+
121
+ ```json
122
+ "ChartValueLabels": true
123
+ ```
124
+
125
+ or, with options:
126
+
127
+ ```json
128
+ "ChartValueLabels": {
129
+ "Decimals": 1,
130
+ "Position": "top",
131
+ "Color": "Dataset"
132
+ }
133
+ ```
134
+
135
+ | Property | Type | Default | Description |
136
+ |----------|------|---------|-------------|
137
+ | `Enabled` | boolean | `true` | `false` turns the labels off while keeping the rest of the block |
138
+ | `Datasets` | string | `"All"` | `"All"` labels every dataset except those with `ValueLabels: false`; `"OptIn"` labels only datasets with `ValueLabels: true` |
139
+ | `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 |
140
+ | `Decimals` | number | — | Fixed decimal places. Without it the value is shown as is, with floating-point noise trimmed |
141
+ | `Color` | string | chart text colour | Any CSS colour, or `"Dataset"` to draw each label in its series' border colour |
142
+ | `FontSize` | number | `11` | Pixels |
143
+ | `FontWeight` | string | `"normal"` | Any CSS font weight |
144
+ | `Offset` | number | `4` | Pixels between the point marker and its label |
145
+ | `Padding` | number | `2` | Pixels around the text that count toward its box when checking for overlap |
146
+ | `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 |
147
+ | `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 |
148
+ | `HaloColor` | string | from the text colour | Any CSS colour |
149
+ | `HaloWidth` | number | `3` | Pixels |
150
+
151
+ Labels are placed in dataset order and then point order, so list the series
152
+ whose values matter most first: it keeps its labels when series crowd each
153
+ other. A label that would leave the plot area is flipped to the other side of
154
+ its point and kept inside the plot. With `Position: "top"`, the chart reserves
155
+ room above the plot for the highest label, unless the configuration already sets
156
+ `options.layout.padding`. Blank points and datasets hidden from the legend get no
157
+ labels.
158
+
109
159
  ## Examples
110
160
 
111
161
  ### 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.4",
4
4
  "description": "Pict dynamic forms",
5
5
  "main": "source/Pict-Section-Form.js",
6
6
  "directories": {
@@ -345,6 +345,326 @@ 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
+ // Raw and Address datasets reach Chart.js as written, so they carry the flag as ValueLabels
468
+ const tmpFlag = (typeof (tmpDataset.pictValueLabels) === 'boolean') ? tmpDataset.pictValueLabels : tmpDataset.ValueLabels;
469
+ const tmpIncluded = (tmpFlag === true) || (tmpAllDatasets && (tmpFlag !== false));
470
+ if (!tmpIncluded)
471
+ {
472
+ continue;
473
+ }
474
+ if ((typeof (pChart.isDatasetVisible) === 'function') && !pChart.isDatasetVisible(i))
475
+ {
476
+ continue;
477
+ }
478
+ const tmpMeta = pChart.getDatasetMeta(i);
479
+ if (!tmpMeta || !Array.isArray(tmpMeta.data))
480
+ {
481
+ continue;
482
+ }
483
+ const tmpValueAxis = (tmpMeta.vScale && tmpMeta.vScale.axis) || 'y';
484
+ for (let j = 0; j < tmpMeta.data.length; j++)
485
+ {
486
+ const tmpElement = tmpMeta.data[j];
487
+ if (!tmpElement || tmpElement.skip)
488
+ {
489
+ continue;
490
+ }
491
+ let tmpValue = (tmpMeta.controller && (typeof (tmpMeta.controller.getParsed) === 'function')) ? tmpMeta.controller.getParsed(j) : tmpDataset.data[j];
492
+ if ((typeof (tmpValue) === 'object') && (tmpValue !== null))
493
+ {
494
+ tmpValue = (tmpValueAxis in tmpValue) ? tmpValue[tmpValueAxis] : tmpValue.y;
495
+ }
496
+ const tmpText = this._formatChartValueLabel(tmpValue, pConfiguration);
497
+ if (tmpText === null)
498
+ {
499
+ continue;
500
+ }
501
+ const tmpPosition = (typeof (tmpElement.tooltipPosition) === 'function') ? tmpElement.tooltipPosition(false) : tmpElement;
502
+ if (!isFinite(tmpPosition.x) || !isFinite(tmpPosition.y))
503
+ {
504
+ continue;
505
+ }
506
+ const tmpWidth = fMeasureText(tmpText) + (2 * pConfiguration.Padding);
507
+ const tmpRadius = (tmpElement.options && isFinite(tmpElement.options.radius)) ? Number(tmpElement.options.radius) : 0;
508
+ const tmpGap = tmpRadius + pConfiguration.Offset;
509
+ // Arcs (pie, doughnut, polar area) label their centroid
510
+ let tmpPlacement = (typeof (tmpElement.outerRadius) === 'number') ? 'center' : pConfiguration.Position;
511
+ // A bar below its base reads from its far end, so its label goes underneath
512
+ if ((tmpPlacement !== 'center') && ('base' in tmpElement) && (Number(tmpValue) < 0))
513
+ {
514
+ tmpPlacement = (tmpPlacement === 'top') ? 'bottom' : 'top';
515
+ }
516
+ const tmpAboveTop = tmpPosition.y - tmpGap - tmpHeight;
517
+ const tmpBelowTop = tmpPosition.y + tmpGap;
518
+ const fClampTop = (pTop) => Math.max(tmpArea.top, Math.min(pTop, tmpArea.bottom - tmpHeight));
519
+ let tmpTop = tmpPosition.y - (tmpHeight / 2);
520
+ // The other side of the point, tried when the first choice collides with a kept label
521
+ let tmpAlternateTop = null;
522
+ if (tmpPlacement === 'top')
523
+ {
524
+ const tmpFits = (tmpAboveTop >= tmpArea.top);
525
+ tmpTop = tmpFits ? tmpAboveTop : tmpBelowTop;
526
+ tmpAlternateTop = tmpFits ? fClampTop(tmpBelowTop) : null;
527
+ }
528
+ else if (tmpPlacement === 'bottom')
529
+ {
530
+ const tmpFits = ((tmpBelowTop + tmpHeight) <= tmpArea.bottom);
531
+ tmpTop = tmpFits ? tmpBelowTop : tmpAboveTop;
532
+ tmpAlternateTop = tmpFits ? fClampTop(tmpAboveTop) : null;
533
+ }
534
+ tmpTop = fClampTop(tmpTop);
535
+ const tmpLeft = Math.max(tmpArea.left, Math.min(tmpPosition.x - (tmpWidth / 2), tmpArea.right - tmpWidth));
536
+ let tmpColor = pConfiguration.Color || (pChart.options && pChart.options.color) || '#666';
537
+ if (pConfiguration.Color === 'Dataset')
538
+ {
539
+ tmpColor = (tmpElement.options && tmpElement.options.borderColor) || tmpDataset.borderColor || (pChart.options && pChart.options.color) || '#666';
540
+ }
541
+ tmpLabels.push(
542
+ {
543
+ Text: tmpText,
544
+ Color: tmpColor,
545
+ X: tmpLeft + (tmpWidth / 2),
546
+ Y: tmpTop + (tmpHeight / 2),
547
+ Left: tmpLeft,
548
+ Top: tmpTop,
549
+ Width: tmpWidth,
550
+ Height: tmpHeight,
551
+ AlternateTop: tmpAlternateTop,
552
+ DatasetIndex: i,
553
+ Index: j,
554
+ });
555
+ }
556
+ }
557
+ return tmpLabels;
558
+ }
559
+
560
+ /**
561
+ * Keep the labels that fit. A label that would overlap one already kept moves
562
+ * to the other side of its point if that is clear, and is hidden otherwise.
563
+ * Earlier datasets win, then earlier points, so the series listed first keeps
564
+ * its values when series crowd each other.
565
+ *
566
+ * @param {Array<Object>} pLabels - From _collectChartValueLabels.
567
+ * @param {boolean} pHideOverlaps - False keeps every label where it was first placed.
568
+ * @return {Array<Object>} The labels to draw.
569
+ */
570
+ _layoutChartValueLabels(pLabels, pHideOverlaps)
571
+ {
572
+ if (!pHideOverlaps)
573
+ {
574
+ return pLabels;
575
+ }
576
+ const tmpKept = [];
577
+ const fIsClear = (pLeft, pTop, pWidth, pHeight) =>
578
+ {
579
+ for (let j = 0; j < tmpKept.length; j++)
580
+ {
581
+ const tmpOther = tmpKept[j];
582
+ if ((pLeft < tmpOther.Left + tmpOther.Width) && (tmpOther.Left < pLeft + pWidth)
583
+ && (pTop < tmpOther.Top + tmpOther.Height) && (tmpOther.Top < pTop + pHeight))
584
+ {
585
+ return false;
586
+ }
587
+ }
588
+ return true;
589
+ };
590
+ for (let i = 0; i < pLabels.length; i++)
591
+ {
592
+ const tmpLabel = pLabels[i];
593
+ if (fIsClear(tmpLabel.Left, tmpLabel.Top, tmpLabel.Width, tmpLabel.Height))
594
+ {
595
+ tmpKept.push(tmpLabel);
596
+ }
597
+ else if ((typeof (tmpLabel.AlternateTop) === 'number') && fIsClear(tmpLabel.Left, tmpLabel.AlternateTop, tmpLabel.Width, tmpLabel.Height))
598
+ {
599
+ tmpKept.push(Object.assign({}, tmpLabel, { Top: tmpLabel.AlternateTop, Y: tmpLabel.AlternateTop + (tmpLabel.Height / 2), AlternateTop: null }));
600
+ }
601
+ }
602
+ return tmpKept;
603
+ }
604
+
605
+ /**
606
+ * The halo drawn behind label text so it stays readable over grid lines and
607
+ * other series: dark behind light text, light behind dark text.
608
+ *
609
+ * @param {string} pTextColor - The chart's text colour.
610
+ * @return {string} The halo colour.
611
+ */
612
+ _chartValueLabelHaloColor(pTextColor)
613
+ {
614
+ const tmpMatch = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(pTextColor || '');
615
+ if (tmpMatch)
616
+ {
617
+ const tmpLuminance = ((0.299 * Number(tmpMatch[1])) + (0.587 * Number(tmpMatch[2])) + (0.114 * Number(tmpMatch[3]))) / 255;
618
+ if (tmpLuminance > 0.5)
619
+ {
620
+ return 'rgba(0, 0, 0, 0.75)';
621
+ }
622
+ }
623
+ return 'rgba(255, 255, 255, 0.85)';
624
+ }
625
+
626
+ /**
627
+ * Draw each point's value on a chart's canvas, after its datasets.
628
+ *
629
+ * @param {Object} pChart - The Chart.js instance.
630
+ * @param {Object} pConfiguration - From resolveChartValueLabelConfiguration.
631
+ * @return {number} How many labels were drawn.
632
+ */
633
+ drawChartValueLabels(pChart, pConfiguration)
634
+ {
635
+ const tmpContext = pChart && pChart.ctx;
636
+ if (!tmpContext || !pChart.chartArea)
637
+ {
638
+ return 0;
639
+ }
640
+ const tmpFamily = (pChart.options && pChart.options.font && pChart.options.font.family) || 'sans-serif';
641
+ tmpContext.save();
642
+ tmpContext.font = `${pConfiguration.FontWeight} ${pConfiguration.FontSize}px ${tmpFamily}`;
643
+ const tmpLabels = this._layoutChartValueLabels(
644
+ this._collectChartValueLabels(pChart, pConfiguration, (pText) => tmpContext.measureText(pText).width),
645
+ pConfiguration.HideOverlaps !== false);
646
+ tmpContext.textAlign = 'center';
647
+ tmpContext.textBaseline = 'middle';
648
+ const tmpHaloWidth = parseFloat(pConfiguration.HaloWidth);
649
+ if (pConfiguration.Halo !== false)
650
+ {
651
+ tmpContext.lineJoin = 'round';
652
+ tmpContext.lineWidth = (isFinite(tmpHaloWidth) && (tmpHaloWidth > 0)) ? tmpHaloWidth : 3;
653
+ tmpContext.strokeStyle = pConfiguration.HaloColor || this._chartValueLabelHaloColor(pChart.options && pChart.options.color);
654
+ }
655
+ for (let i = 0; i < tmpLabels.length; i++)
656
+ {
657
+ if (pConfiguration.Halo !== false)
658
+ {
659
+ tmpContext.strokeText(tmpLabels[i].Text, tmpLabels[i].X, tmpLabels[i].Y);
660
+ }
661
+ tmpContext.fillStyle = tmpLabels[i].Color;
662
+ tmpContext.fillText(tmpLabels[i].Text, tmpLabels[i].X, tmpLabels[i].Y);
663
+ }
664
+ tmpContext.restore();
665
+ return tmpLabels.length;
666
+ }
667
+
348
668
  /**
349
669
  * Resolve the text and grid colours a chart should draw with from the page
350
670
  * around its canvas, so the canvas follows the host's light or dark theme the
@@ -932,6 +1252,11 @@ class CustomInputHandler extends libPictSectionInputExtension
932
1252
  tmpDataObject.pictLegendGroup = tmpCurrentSolverExpression.LegendGroup;
933
1253
  }
934
1254
 
1255
+ if (typeof (tmpCurrentSolverExpression.ValueLabels) === 'boolean')
1256
+ {
1257
+ tmpDataObject.pictValueLabels = tmpCurrentSolverExpression.ValueLabels;
1258
+ }
1259
+
935
1260
  if (tmpParsingConfiguration.ObjectType === 'array')
936
1261
  {
937
1262
  if (Array.isArray(tmpSolvedDataSet))
@@ -1064,6 +1389,26 @@ class CustomInputHandler extends libPictSectionInputExtension
1064
1389
  tmpChartConfiguration.options.plugins.legend = Object.assign({}, tmpChartConfiguration.options.plugins.legend, { display: false });
1065
1390
  }
1066
1391
 
1392
+ const tmpValueLabelConfiguration = this.resolveChartValueLabelConfiguration(pInput);
1393
+ if (tmpValueLabelConfiguration)
1394
+ {
1395
+ if (!Array.isArray(tmpChartConfiguration.plugins))
1396
+ {
1397
+ tmpChartConfiguration.plugins = [];
1398
+ }
1399
+ tmpChartConfiguration.plugins.push(this.createChartValueLabelPlugin(tmpValueLabelConfiguration));
1400
+ // Room above the plot for the topmost point's label, so it does not have to flip below its point
1401
+ if ((tmpValueLabelConfiguration.Position === 'top') && (typeof (tmpChartConfiguration.options?.layout?.padding) === 'undefined'))
1402
+ {
1403
+ if (typeof (tmpChartConfiguration.options) !== 'object' || tmpChartConfiguration.options === null)
1404
+ {
1405
+ tmpChartConfiguration.options = {};
1406
+ }
1407
+ tmpChartConfiguration.options.layout = Object.assign({}, tmpChartConfiguration.options.layout,
1408
+ { padding: { top: tmpValueLabelConfiguration.FontSize + tmpValueLabelConfiguration.Offset + (2 * tmpValueLabelConfiguration.Padding) } });
1409
+ }
1410
+ }
1411
+
1067
1412
  const tmpChartHeight = parseFloat(tmpPictform.ChartHeight);
1068
1413
  if (isFinite(tmpChartHeight) && (tmpChartHeight > 0))
1069
1414
  {