Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ui/contextitems/ve.ui.SumCellsContextItem.js

raw symbols SCIP
1 /*!
2 * VisualEditor SumCellsContextItem class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Show the sum and average of numeric values across a table selection.
9 *
10 * @class
11 * @extends ve.ui.LinearContextItem
12 *
13 * @param {ve.ui.LinearContext} context Context the item is in
14 * @param {ve.dm.Model} model Model the item is related to
15 * @param {Object} [config] Configuration options
16 */
17 ve.ui.SumCellsContextItem = function VeUiSumCellsContextItem( context, model, config ) {
18 // Parent constructor
19 ve.ui.SumCellsContextItem.super.call( this, context, model, config );
20
21 // Initialization
22 this.$element.addClass( 've-ui-sumCellsContextItem' );
23 };
24
25 /* Inheritance */
26
27 OO.inheritClass( ve.ui.SumCellsContextItem, ve.ui.LinearContextItem );
28
29 /* Static Properties */
30
31 ve.ui.SumCellsContextItem.static.name = 'sumCells';
32
33 ve.ui.SumCellsContextItem.static.icon = 'mathematics';
34
35 ve.ui.SumCellsContextItem.static.editable = false;
36
37 ve.ui.SumCellsContextItem.static.embeddable = false;
38
39 /* Methods */
40
41 /**
42 * @inheritdoc
43 */
44 ve.ui.SumCellsContextItem.static.isCompatibleWith = function ( model ) {
45 return model instanceof ve.dm.Node && model.isCellable();
46 };
47
48 /**
49 * @inheritdoc
50 */
51 ve.ui.SumCellsContextItem.prototype.setup = function () {
52 // Parent method
53 ve.ui.SumCellsContextItem.super.prototype.setup.apply( this, arguments );
54
55 // If not disabled, selection must be table and spanning multiple matrix cells
56 const selection = this.getFragment().getSurface().getSelection(),
57 documentModel = this.getFragment().getDocument(),
58 documentView = this.context.getSurface().getView().getDocument();
59
60 let count = 0;
61 // There's some situations involving transclusion table cells which
62 // can make us have a LinearSelection here, so make sure this will
63 // work:
64 let sum;
65 if ( selection instanceof ve.dm.TableSelection ) {
66 const cells = selection.getMatrixCells( documentModel, true );
67 if ( cells.length > 1 ) {
68 sum = cells.reduce( ( s, cell ) => {
69 let number;
70 if ( !cell.isPlaceholder() ) {
71 // Get text from view rendering to catch numbers in alien nodes, etc.
72 const viewCell = documentView.getBranchNodeFromOffset( cell.node.getRange().start );
73 number = ve.init.platform.parseNumber(
74 viewCell.$element.text()
75 );
76 if ( !isNaN( number ) ) {
77 count++;
78 return s + number;
79 }
80 }
81 return s;
82 }, 0 );
83 }
84 }
85
86 // Only show if more than one numeric value was selected
87 if ( count > 1 ) {
88 this.setLabel(
89 ve.msg( 'visualeditor-table-sum',
90 ve.init.platform.formatNumber( sum ),
91 ve.init.platform.formatNumber( sum / count )
92 )
93 );
94 } else {
95 this.$element.detach();
96 }
97 };
98
99 /* Registration */
100
101 ve.ui.contextItemFactory.register( ve.ui.SumCellsContextItem );