Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ui/actions/ve.ui.TableAction.js

raw symbols SCIP
1 /*!
2 * VisualEditor ContentEditable TableNode class.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Table action.
10 *
11 * @class
12 * @extends ve.ui.Action
13 *
14 * @constructor
15 * @param {ve.ui.Surface} surface Surface to act on
16 * @param {string} [source]
17 */
18 ve.ui.TableAction = function VeUiTableAction() {
19 // Parent constructor
20 ve.ui.TableAction.super.apply( this, arguments );
21 };
22
23 /* Inheritance */
24
25 OO.inheritClass( ve.ui.TableAction, ve.ui.Action );
26
27 /* Static Properties */
28
29 ve.ui.TableAction.static.name = 'table';
30
31 ve.ui.TableAction.static.methods = [
32 'create', 'insert', 'moveRelative', 'move', 'delete', 'importTable',
33 'changeCellStyle', 'mergeCells', 'enterTableCell', 'exitTableCell'
34 ];
35
36 /* Methods */
37
38 /**
39 * Creates a new table.
40 *
41 * @param {Object} [options] Table creation options
42 * @param {boolean} [options.caption] Include a caption
43 * @param {boolean} [options.header] Include a header row
44 * @param {number} [options.cols=4] Number of columns
45 * @param {number} [options.rows=3] Number of rows (not including optional header row)
46 * @param {Object} [options.type='table'] Table node type, must inherit from table
47 * @param {Object} [options.attributes] Attributes to give the table
48 * @return {boolean} Action was executed
49 */
50 ve.ui.TableAction.prototype.create = function ( options ) {
51 options = options || {};
52
53 const type = options.type || 'table';
54 const tableElement = { type: type };
55 const surfaceModel = this.surface.getModel();
56 const fragment = surfaceModel.getFragment();
57 const numberOfCols = options.cols || 4;
58 const numberOfRows = options.rows || 3;
59
60 if ( !( fragment.getSelection() instanceof ve.dm.LinearSelection ) ) {
61 return false;
62 }
63
64 if ( options.attributes ) {
65 tableElement.attributes = ve.copy( options.attributes );
66 }
67
68 const data = [];
69 data.push( tableElement );
70 if ( options.caption ) {
71 data.push(
72 { type: 'tableCaption' },
73 { type: 'paragraph', internal: { generated: 'wrapper' } },
74 { type: '/paragraph' },
75 { type: '/tableCaption' }
76 );
77 }
78 data.push( { type: 'tableSection', attributes: { style: 'body' } } );
79 if ( options.header ) {
80 ve.batchPush( data, ve.dm.TableRowNode.static.createData( { style: 'header', cellCount: numberOfCols } ) );
81 }
82 for ( let i = 0; i < numberOfRows; i++ ) {
83 ve.batchPush( data, ve.dm.TableRowNode.static.createData( { style: 'data', cellCount: numberOfCols } ) );
84 }
85 data.push( { type: '/tableSection' } );
86 data.push( { type: '/' + type } );
87
88 fragment.insertContent( data, false );
89 surfaceModel.setSelection( new ve.dm.TableSelection(
90 fragment.getSelection().getRange(), 0, 0, 0, 0
91 ) );
92
93 ve.track( 'activity.table', { action: 'create' } );
94
95 return true;
96 };
97
98 /**
99 * Inserts a new row or column into the currently focused table.
100 *
101 * @param {string} mode Insertion mode; 'row' to insert a new row, 'col' for a new column
102 * @param {string} position Insertion position; 'before' to insert before the current selection,
103 * 'after' to insert after it
104 * @return {boolean} Action was executed
105 */
106 ve.ui.TableAction.prototype.insert = function ( mode, position ) {
107 const surfaceModel = this.surface.getModel();
108
109 let selection = surfaceModel.getSelection();
110
111 if ( !( selection instanceof ve.dm.TableSelection ) ) {
112 return false;
113 }
114
115 let index;
116 if ( mode === 'col' ) {
117 index = position === 'before' ? selection.startCol : selection.endCol;
118 } else {
119 index = position === 'before' ? selection.startRow : selection.endRow;
120 }
121
122 const documentModel = surfaceModel.getDocument();
123 if ( position === 'before' ) {
124 if ( mode === 'col' ) {
125 selection = selection.newFromAdjustment( documentModel, 1, 0 );
126 } else {
127 selection = selection.newFromAdjustment( documentModel, 0, 1 );
128 }
129 surfaceModel.setSelection( selection );
130 }
131 this.insertRowOrCol( selection.getTableNode( documentModel ), mode, index, position, selection );
132
133 ve.track( 'activity.table', { action: 'insert-' + mode } );
134
135 return true;
136 };
137
138 /**
139 * Move a column or row relative to its current position
140 *
141 * @param {string} mode Move mode; 'col' or 'row'
142 * @param {string} direction Direction; 'before' or 'after'
143 * @return {boolean} Action was executed
144 */
145 ve.ui.TableAction.prototype.moveRelative = function ( mode, direction ) {
146 const surfaceModel = this.surface.getModel(),
147 selection = surfaceModel.getSelection();
148
149 if ( !( selection instanceof ve.dm.TableSelection ) ) {
150 return false;
151 }
152
153 const documentModel = surfaceModel.getDocument();
154 const matrix = selection.getTableNode( documentModel ).getMatrix();
155 let index;
156 if ( mode === 'row' ) {
157 if ( direction === 'before' ) {
158 index = Math.max( 0, selection.startRow - 1 );
159 } else {
160 index = Math.min( matrix.getRowCount(), selection.endRow + 2 );
161 }
162 } else {
163 if ( direction === 'before' ) {
164 index = Math.max( 0, selection.startCol - 1 );
165 } else {
166 index = Math.min( matrix.getMaxColCount(), selection.endCol + 2 );
167 }
168 }
169 return this.move( mode, index );
170 };
171
172 /**
173 * Move a column or row.
174 *
175 * @param {string} mode Move mode; 'col' or 'row'
176 * @param {number} index Row or column index to move to
177 * @return {boolean} Action was executed
178 */
179 ve.ui.TableAction.prototype.move = function ( mode, index ) {
180 const surfaceModel = this.surface.getModel(),
181 selection = surfaceModel.getSelection();
182
183 if ( !( selection instanceof ve.dm.TableSelection ) ) {
184 return false;
185 }
186
187 const documentModel = surfaceModel.getDocument();
188 const tableNode = selection.getTableNode( documentModel );
189 const matrix = tableNode.getMatrix();
190
191 let removedMatrix, newOffsets;
192 if ( mode === 'row' ) {
193 removedMatrix = this.deleteRowsOrColumns( matrix, mode, selection.startRow, selection.endRow );
194 if ( index > selection.endRow ) {
195 index = index - selection.getRowCount();
196 }
197 newOffsets = [
198 selection.fromCol,
199 index,
200 selection.toCol,
201 index + selection.getRowCount() - 1
202 ];
203 } else {
204 removedMatrix = this.deleteRowsOrColumns( matrix, mode, selection.startCol, selection.endCol );
205 if ( index > selection.endCol ) {
206 index = index - selection.getColCount();
207 }
208 newOffsets = [
209 index,
210 selection.fromRow,
211 index + selection.getColCount() - 1,
212 selection.toRow
213 ];
214 }
215 let position;
216 if ( index === 0 ) {
217 position = 'before';
218 } else {
219 index--;
220 position = 'after';
221 }
222 for ( let i = removedMatrix.length - 1; i >= 0; i-- ) {
223 this.insertRowOrCol( tableNode, mode, index, position, null, removedMatrix[ i ] );
224 }
225 // Only set selection once for performance
226 surfaceModel.setSelection( new ve.dm.TableSelection(
227 // tableNode range was changed by deletion
228 tableNode.getOuterRange(),
229 newOffsets[ 0 ], newOffsets[ 1 ], newOffsets[ 2 ], newOffsets[ 3 ]
230 ) );
231
232 ve.track( 'activity.table', { action: 'move-' + mode } );
233
234 return true;
235 };
236
237 /**
238 * Deletes selected rows, columns, or the whole table.
239 *
240 * @param {string} mode Deletion mode; 'row' to delete rows, 'col' for columns, 'table' to remove the whole table
241 * @return {boolean} Action was executed
242 */
243 ve.ui.TableAction.prototype.delete = function ( mode ) {
244 const selection = this.getTableSelectionFromSelection();
245
246 if ( !( selection instanceof ve.dm.TableSelection ) ) {
247 return false;
248 }
249
250 const documentModel = this.surface.getModel().getDocument();
251 const tableNode = selection.getTableNode( documentModel );
252 // Either delete the table or rows or columns
253 if ( mode === 'table' ) {
254 this.deleteTable( tableNode );
255 } else {
256 let minIndex, maxIndex, isFull;
257 if ( mode === 'col' ) {
258 minIndex = selection.startCol;
259 maxIndex = selection.endCol;
260 isFull = selection.isFullRow( documentModel );
261 } else {
262 minIndex = selection.startRow;
263 maxIndex = selection.endRow;
264 isFull = selection.isFullCol( documentModel );
265 }
266 // Delete the whole table if all rows or cols get deleted
267 if ( isFull ) {
268 this.deleteTable( tableNode );
269 } else {
270 this.deleteRowsOrColumns( tableNode.matrix, mode, minIndex, maxIndex );
271 }
272 }
273
274 ve.track( 'activity.table', { action: 'delete' + ( mode !== 'table' ? ( '-' + mode ) : '' ) } );
275
276 return true;
277 };
278
279 /**
280 * Import a table at the current selection, overwriting data cell by cell
281 *
282 * @param {ve.dm.TableNode} importedTableNode Table node to import
283 * @param {boolean} importInternalList Import the table document's internalLiist
284 * @return {boolean} Action was executed
285 */
286 ve.ui.TableAction.prototype.importTable = function ( importedTableNode, importInternalList ) {
287 const importedMatrix = importedTableNode.getMatrix(),
288 surfaceModel = this.surface.getModel(),
289 documentModel = surfaceModel.getDocument(),
290 selection = surfaceModel.getSelection(),
291 tableNode = selection.getTableNode( documentModel ),
292 matrix = tableNode.getMatrix();
293
294 let i, l;
295 // Increase size of table to fit imported table
296 for ( i = 0, l = selection.startRow + importedMatrix.getRowCount() - matrix.getRowCount(); i < l; i++ ) {
297 this.insertRowOrCol( tableNode, 'row', matrix.getRowCount() - 1, 'after' );
298 }
299 for ( i = 0, l = selection.startCol + importedMatrix.getMaxColCount() - matrix.getMaxColCount(); i < l; i++ ) {
300 this.insertRowOrCol( tableNode, 'col', matrix.getMaxColCount() - 1, 'after' );
301 }
302 let row, col, cell;
303 // Unmerge all cells in the target area
304 for ( row = importedMatrix.getRowCount() - 1; row >= 0; row-- ) {
305 for ( col = importedMatrix.getColCount( row ) - 1; col >= 0; col-- ) {
306 cell = matrix.getCell( selection.fromRow + row, selection.fromCol + col );
307 // Missing cell(s), add cell(s) onto the end of the row
308 while ( !cell ) {
309 surfaceModel.change(
310 ve.dm.TransactionBuilder.static.newFromInsertion(
311 documentModel, matrix.getRowNode( selection.fromRow + row ).getRange().end,
312 ve.dm.TableCellNode.static.createData()
313 )
314 );
315 cell = matrix.getCell( selection.fromRow + row, selection.fromCol + col );
316 }
317 if ( cell.isPlaceholder() || cell.node.getColspan() > 1 || cell.node.getRowspan() > 1 ) {
318 this.unmergeCell( matrix, cell.owner );
319 }
320 }
321 }
322 // Overwrite data
323 for ( row = importedMatrix.getRowCount() - 1; row >= 0; row-- ) {
324 for ( col = importedMatrix.getColCount( row ) - 1; col >= 0; col-- ) {
325 cell = matrix.getCell( selection.fromRow + row, selection.fromCol + col );
326 const cellRange = cell.node.getRange();
327 const importedCell = importedMatrix.getCell( row, col );
328 if ( !importedCell ) {
329 // Cell not found in source table. Likely some sort of invalid or sparse
330 // table matrix (T262842). Just ignore the empty cell.
331 continue;
332 }
333 if ( importedCell.node.type !== cell.node.type ) {
334 // Since the imported cell isn't the same type as the
335 // existing cell, we can't quite trust our assumptions about
336 // how it's supposed to work. As such, it's safer to outright
337 // replace the cell rather than trying to be clever and switch
338 // out the attributes / data. We shouldn't have gotten to this
339 // point without it being Cellable, so this should at least
340 // work.
341 surfaceModel.change( ve.dm.TransactionBuilder.static.newFromReplacement(
342 documentModel, cell.node.getOuterRange(),
343 importedTableNode.getDocument().getData( importedCell.node.getOuterRange() )
344 ) );
345 } else if ( !importedCell.isPlaceholder() ) {
346 // Remove the existing cell contents
347 surfaceModel.change( ve.dm.TransactionBuilder.static.newFromRemoval( documentModel, cellRange ) );
348 // Attribute changes are performed separately, and removing the whole
349 // cell could change the dimensions of the table
350 const txBuilders = [
351 ve.dm.TransactionBuilder.static.newFromAttributeChanges.bind( null,
352 documentModel, cellRange.start - 1,
353 ve.copy( importedCell.node.element.attributes )
354 )
355 ];
356 if ( importInternalList ) {
357 txBuilders.push(
358 ve.dm.TransactionBuilder.static.newFromDocumentInsertion.bind( null,
359 documentModel, cellRange.start,
360 importedTableNode.getDocument(),
361 importedCell.node.getRange()
362 )
363 );
364 } else {
365 txBuilders.push(
366 ve.dm.TransactionBuilder.static.newFromInsertion.bind( null,
367 documentModel, cellRange.start,
368 importedTableNode.getDocument().getData( importedCell.node.getRange() )
369 )
370 );
371 }
372 // Perform the insertion as a separate change so the internalList offsets are correct
373 txBuilders.forEach( ( txBuilder ) => {
374 surfaceModel.change( txBuilder() );
375 } );
376 } else {
377 // Remove the existing cell completely
378 surfaceModel.change( ve.dm.TransactionBuilder.static.newFromRemoval( documentModel, cell.node.getOuterRange() ) );
379 }
380 }
381 }
382 surfaceModel.setSelection(
383 new ve.dm.TableSelection(
384 tableNode.getOuterRange(),
385 selection.startCol, selection.startRow,
386 selection.startCol + importedMatrix.getMaxColCount() - 1,
387 selection.startRow + importedMatrix.getRowCount() - 1
388 )
389 );
390 return true;
391 };
392
393 /**
394 * Change cell style
395 *
396 * @param {string} style Cell style; 'header' or 'data'
397 * @return {boolean} Action was executed
398 */
399 ve.ui.TableAction.prototype.changeCellStyle = function ( style ) {
400 const surfaceModel = this.surface.getModel(),
401 selection = surfaceModel.getSelection();
402
403 if ( !( selection instanceof ve.dm.TableSelection ) ) {
404 return false;
405 }
406
407 const txBuilders = [];
408 const documentModel = surfaceModel.getDocument();
409 const ranges = selection.getOuterRanges( documentModel );
410 for ( let i = ranges.length - 1; i >= 0; i-- ) {
411 txBuilders.push(
412 ve.dm.TransactionBuilder.static.newFromAttributeChanges.bind( null,
413 documentModel, ranges[ i ].start, { style: style }
414 )
415 );
416 }
417 txBuilders.forEach( ( txBuilder ) => {
418 surfaceModel.change( txBuilder() );
419 } );
420
421 ve.track( 'activity.table', { action: 'style-' + style } );
422
423 return true;
424 };
425
426 /**
427 * Merge multiple cells into one, or split a merged cell.
428 *
429 * @return {boolean} Action was executed
430 */
431 ve.ui.TableAction.prototype.mergeCells = function () {
432 const surfaceModel = this.surface.getModel(),
433 selection = surfaceModel.getSelection();
434
435 if ( !( selection instanceof ve.dm.TableSelection ) ) {
436 return false;
437 }
438
439 const txBuilders = [];
440 const documentModel = surfaceModel.getDocument();
441 const matrix = selection.getTableNode( documentModel ).getMatrix();
442 let cells;
443 if ( selection.isSingleCell( documentModel ) ) {
444 // Split
445 cells = selection.getMatrixCells( documentModel );
446 this.unmergeCell( matrix, cells[ 0 ] );
447
448 ve.track( 'activity.table', { action: 'cell-split' } );
449 } else {
450 // Merge
451 if ( !selection.isMergeable( documentModel ) ) {
452 return false;
453 }
454 cells = selection.getMatrixCells( documentModel );
455 txBuilders.push(
456 ve.dm.TransactionBuilder.static.newFromAttributeChanges.bind( null,
457 documentModel, cells[ 0 ].node.getOuterRange().start,
458 {
459 colspan: 1 + selection.endCol - selection.startCol,
460 rowspan: 1 + selection.endRow - selection.startRow
461 }
462 )
463 );
464
465 let i, l;
466 let contentData;
467 // Find first cell with content
468 for ( i = 0, l = cells.length; i < l; i++ ) {
469 contentData = new ve.dm.ElementLinearData(
470 documentModel.getStore(),
471 documentModel.getData( cells[ i ].node.getRange() )
472 );
473 if ( contentData.hasContent() ) {
474 // If the first cell contains content, we don't need to move any content
475 if ( !i ) {
476 contentData = null;
477 }
478 break;
479 }
480 }
481 // Remove placeholders
482 for ( i = cells.length - 1; i >= 1; i-- ) {
483 txBuilders.push(
484 ve.dm.TransactionBuilder.static.newFromRemoval.bind( null,
485 documentModel, cells[ i ].node.getOuterRange()
486 )
487 );
488 }
489 // Move the first-found content to the merged cell
490 if ( contentData ) {
491 txBuilders.push(
492 ve.dm.TransactionBuilder.static.newFromReplacement.bind( null,
493 documentModel, cells[ 0 ].node.getRange(), contentData.data
494 )
495 );
496 }
497 txBuilders.forEach( ( txBuilder ) => {
498 surfaceModel.change( txBuilder() );
499 } );
500
501 let hasNonPlaceholders, r, c, cell;
502 // Check for rows filled with entirely placeholders. If such a row exists, delete it.
503 for ( r = selection.endRow; r >= selection.startRow; r-- ) {
504 hasNonPlaceholders = false;
505 for ( c = 0; ( cell = matrix.getCell( r, c ) ) !== undefined; c++ ) {
506 if ( cell && !cell.isPlaceholder() ) {
507 hasNonPlaceholders = true;
508 break;
509 }
510 }
511 if ( !hasNonPlaceholders ) {
512 this.deleteRowsOrColumns( matrix, 'row', r, r );
513 }
514 }
515
516 // Check for columns filled with entirely placeholders. If such a column exists, delete it.
517 for ( c = selection.endCol; c >= selection.startCol; c-- ) {
518 hasNonPlaceholders = false;
519 for ( r = 0; ( cell = matrix.getCell( r, c ) ) !== undefined; r++ ) {
520 if ( cell && !cell.isPlaceholder() ) {
521 hasNonPlaceholders = true;
522 break;
523 }
524 }
525 if ( !hasNonPlaceholders ) {
526 this.deleteRowsOrColumns( matrix, 'col', c, c );
527 }
528 }
529
530 ve.track( 'activity.table', { action: 'cell-merge' } );
531 }
532 return true;
533 };
534
535 /**
536 * Enter a table cell for editing
537 *
538 * @return {boolean} Action was executed
539 */
540 ve.ui.TableAction.prototype.enterTableCell = function () {
541 const tableNode = this.findClosestTableViewNode();
542
543 if ( !tableNode ) {
544 return false;
545 }
546
547 tableNode.setEditing( true );
548 this.surface.getView().focus();
549 return true;
550 };
551
552 /**
553 * Exit a table cell for table-structure-editing
554 *
555 * @return {boolean} Action was executed
556 */
557 ve.ui.TableAction.prototype.exitTableCell = function () {
558 const tableNode = this.findClosestTableViewNode();
559
560 if ( !tableNode ) {
561 return false;
562 }
563
564 tableNode.setEditing( false );
565 this.surface.getView().focus();
566 return true;
567 };
568
569 /* Low-level API */
570 // TODO: This API does only depends on the model so it should possibly be moved
571
572 /**
573 * Deletes a whole table.
574 *
575 * @param {ve.dm.TableNode} tableNode Table node
576 */
577 ve.ui.TableAction.prototype.deleteTable = function ( tableNode ) {
578 this.surface.getModel().getLinearFragment( tableNode.getOuterRange() ).delete();
579 };
580
581 /**
582 * Unmerge a cell
583 *
584 * @param {ve.dm.TableMatrix} matrix Table matrix the cell is in
585 * @param {ve.dm.TableMatrixCell} ownerCell The cell to unmerge
586 */
587 ve.ui.TableAction.prototype.unmergeCell = function ( matrix, ownerCell ) {
588 const txBuilders = [],
589 colspan = ownerCell.node.getColspan(),
590 rowspan = ownerCell.node.getRowspan(),
591 surfaceModel = this.surface.getModel(),
592 documentModel = surfaceModel.getDocument();
593
594 txBuilders.push(
595 ve.dm.TransactionBuilder.static.newFromAttributeChanges.bind( null,
596 documentModel, ownerCell.node.getOuterRange().start,
597 { colspan: 1, rowspan: 1 }
598 )
599 );
600 for ( let row = ownerCell.row + rowspan - 1; row >= ownerCell.row; row-- ) {
601 for ( let col = ownerCell.col + colspan - 1; col >= ownerCell.col; col-- ) {
602 const cell = matrix.getCell( row, col );
603 if ( cell.isPlaceholder() ) {
604 txBuilders.push(
605 this.replacePlaceholder(
606 matrix,
607 cell,
608 { style: ownerCell.node.getStyle() }
609 )
610 );
611 }
612 }
613 }
614 txBuilders.forEach( ( txBuilder ) => {
615 surfaceModel.change( txBuilder() );
616 } );
617 };
618
619 /**
620 * Inserts a new row or column.
621 *
622 * Example: a new row can be inserted after the 2nd row using
623 *
624 * insertRowOrCol( table, 'row', 1, 'after' );
625 *
626 * @param {ve.dm.TableNode} tableNode Table node
627 * @param {string} mode Insertion mode; 'row' or 'col'
628 * @param {number} index Row or column index of the base row or column.
629 * @param {string} position Insertion position; 'before' or 'after'
630 * @param {ve.dm.TableSelection} [selection] Selection to move to after insertion
631 * @param {Object} [dataMatrixLine] Data to insert
632 * @param {Array} [dataMatrixLine.rowData] Row data if inserting a row
633 * @param {ve.dm.TableMatrixCell[]} [dataMatrixLine.cells] Table cells to insert
634 */
635 ve.ui.TableAction.prototype.insertRowOrCol = function ( tableNode, mode, index, position, selection, dataMatrixLine ) {
636 const matrix = tableNode.matrix,
637 insertCells = [],
638 txBuilders = [],
639 updated = {},
640 inserts = [],
641 surfaceModel = this.surface.getModel();
642
643 let insertData = [];
644 const before = position === 'before';
645
646 // Note: when we insert a new row (or column) we might need to increment a span property
647 // instead of inserting a new cell.
648 // To achieve this we look at the so called base row and a so called reference row.
649 // The base row is the one after or before which the new row will be inserted.
650 // The reference row is the one which is currently at the place of the new one.
651 // E.g. consider inserting a new row after the second: the base row is the second, the
652 // reference row is the third.
653 // A span must be increased if the base cell and the reference cell have the same 'owner'.
654 // E.g.: C* | P**; C | P* | P**, i.e., one of the two cells might be the owner of the other,
655 // or vice versa, or both a placeholders of a common cell.
656
657 // The index of the reference row or column
658 const refIndex = index + ( before ? -1 : 1 );
659 // Cells of the selected row or column
660 let cells, refCells;
661 if ( mode === 'row' ) {
662 cells = matrix.getRow( index ) || [];
663 refCells = matrix.getRow( refIndex ) || [];
664 } else {
665 cells = matrix.getColumn( index ) || [];
666 refCells = matrix.getColumn( refIndex ) || [];
667 }
668
669 for ( let i = 0, l = Math.max( cells.length, dataMatrixLine ? dataMatrixLine.cells.length : 0 ); i < l; i++ ) {
670 let cell = cells[ i ];
671 if ( !cell ) {
672 if ( dataMatrixLine && dataMatrixLine.cells[ i ] ) {
673 // If we've been given data to fill the empty cells with, do so
674 insertCells.push( dataMatrixLine.cells[ i ] );
675 }
676 // Either way, continue on to the next cell
677 continue;
678 }
679 const refCell = refCells[ i ];
680 // Detect if span update is necessary
681 if ( refCell && ( cell.isPlaceholder() || refCell.isPlaceholder() ) ) {
682 if ( cell.node === refCell.node ) {
683 cell = cell.owner || cell;
684 if ( !updated[ cell.key ] ) {
685 // Note: we can safely record span modifications as they do not affect range offsets.
686 txBuilders.push( this.incrementSpan( cell, mode ) );
687 updated[ cell.key ] = true;
688 }
689 // Resolve merged cell conflicts when moving
690 if ( dataMatrixLine && dataMatrixLine.cells[ i ].owner.data && !dataMatrixLine.cells[ i ].owner.conflicted ) {
691 if ( dataMatrixLine.cells[ i ].isPlaceholder() ) {
692 // If placeholders conflict, collapse their owners
693 dataMatrixLine.cells[ i ].owner.data[ 0 ].attributes.colspan = 1;
694 dataMatrixLine.cells[ i ].owner.data[ 0 ].attributes.rowspan = 1;
695 }
696 // Mark owner (could be self) as conflicted so placeholders know it didn't get inserted
697 dataMatrixLine.cells[ i ].owner.conflicted = true;
698 }
699 continue;
700 }
701 }
702 // If it is not a span changer, we record the base cell as a reference for insertion
703 inserts.push( cell );
704 if ( dataMatrixLine ) {
705 insertCells.push( dataMatrixLine.cells[ i ] );
706 }
707 }
708
709 // Inserting a new row differs completely from inserting a new column:
710 // For a new row, a new row node is created, and inserted relative to an existing row node.
711 // For a new column, new cells are inserted into existing row nodes at appropriate positions,
712 // i.e., relative to an existing cell node.
713 if ( mode === 'row' ) {
714 if ( !dataMatrixLine ) {
715 insertData = ve.dm.TableRowNode.static.createData( {
716 cellCount: inserts.length,
717 style: cells.map( ( c ) => c.node.getStyle() )
718 } );
719 } else {
720 insertData.push( dataMatrixLine.row[ 0 ] );
721 insertCells.forEach( ( c ) => {
722 if ( c && c.data ) {
723 ve.batchPush( insertData, c.data );
724 } else if ( !( c && c.isPlaceholder() && c.owner.data && !c.owner.conflicted ) ) {
725 // If a placeholder, and the owner was not inserted, created a blank cell
726 ve.batchPush( insertData, ve.dm.TableCellNode.static.createData() );
727 }
728 } );
729 insertData.push( dataMatrixLine.row[ 1 ] );
730 }
731 let rowNode;
732 while ( ( rowNode = matrix.getRowNode( index ) ) === undefined ) {
733 index--;
734 }
735 const range = rowNode.getOuterRange();
736 const offset = before ? range.start : range.end;
737 txBuilders.push( ve.dm.TransactionBuilder.static.newFromInsertion.bind( null, surfaceModel.getDocument(), offset, insertData ) );
738 } else {
739 // Make sure that the inserts are in descending offset order
740 // so that the transactions do not affect subsequent range offsets.
741 inserts.sort( ve.dm.TableMatrixCell.static.sortDescending );
742
743 // For inserting a new cell we need to find a reference cell node
744 // which we can use to get a proper insertion offset.
745 for ( let i = 0; i < inserts.length; i++ ) {
746 let cell = inserts[ i ];
747 if ( !cell ) {
748 continue;
749 }
750 // If the cell is a placeholder this will find a close cell node in the same row
751 const refCell = matrix.findClosestCell( cell );
752 let style;
753 let offset;
754 if ( refCell ) {
755 const range = refCell.node.getOuterRange();
756 // If the found cell is before the base cell the new cell must be placed after it, in any case,
757 // Only if the base cell is not a placeholder we have to consider the insert mode.
758 if ( refCell.col < cell.col || ( refCell.col === cell.col && !before ) ) {
759 offset = range.end;
760 } else {
761 offset = range.start;
762 }
763 style = refCell.node.getStyle();
764 } else {
765 // If there are only placeholders in the row, we use the row node's inner range
766 // for the insertion offset
767 const rowNode = matrix.getRowNode( cell.row );
768 if ( !rowNode ) {
769 continue;
770 }
771 const range = rowNode.getRange();
772 offset = before ? range.start : range.end;
773 style = cells[ 0 ].node.getStyle();
774 }
775 let cellData;
776 if ( !dataMatrixLine ) {
777 cellData = ve.dm.TableCellNode.static.createData( { style: style } );
778 } else {
779 cell = dataMatrixLine.cells[ cell.row ];
780 cellData = [];
781 if ( cell && cell.data ) {
782 cellData = cell.data;
783 } else if ( !( cell && cell.isPlaceholder() && cell.owner.data && !cell.owner.conflicted ) ) {
784 // If a placeholder, and the owner was not inserted, created a blank cell
785 cellData = ve.dm.TableCellNode.static.createData();
786 }
787 }
788 txBuilders.push( ve.dm.TransactionBuilder.static.newFromInsertion.bind( null, surfaceModel.getDocument(), offset, cellData ) );
789 }
790 }
791 txBuilders.forEach( ( txBuilder ) => {
792 const tx = txBuilder();
793 selection = selection && selection.translateByTransaction( tx );
794 surfaceModel.change( tx );
795 } );
796 if ( selection ) {
797 surfaceModel.change( null, selection );
798 }
799 };
800
801 /**
802 * Increase the span of a cell by one.
803 *
804 * @param {ve.dm.TableMatrixCell} cell Table matrix cell
805 * @param {string} mode Span to increment; 'row' or 'col'
806 * @return {Function} Zero-argument function returning a ve.dm.Transaction
807 */
808 ve.ui.TableAction.prototype.incrementSpan = function ( cell, mode ) {
809 let data;
810 if ( mode === 'row' ) {
811 data = { rowspan: cell.node.getRowspan() + 1 };
812 } else {
813 data = { colspan: cell.node.getColspan() + 1 };
814 }
815
816 const surfaceModel = this.surface.getModel();
817 return ve.dm.TransactionBuilder.static.newFromAttributeChanges.bind( null, surfaceModel.getDocument(), cell.node.getOuterRange().start, data );
818 };
819
820 /**
821 * Decreases the span of a cell so that the given interval is removed.
822 *
823 * @param {ve.dm.TableMatrixCell} cell Table matrix cell
824 * @param {string} mode Span to decrement 'row' or 'col'
825 * @param {number} minIndex Smallest row or column index (inclusive)
826 * @param {number} maxIndex Largest row or column index (inclusive)
827 * @return {Function} Zero-argument function returning a ve.dm.Transaction
828 */
829 ve.ui.TableAction.prototype.decrementSpan = function ( cell, mode, minIndex, maxIndex ) {
830 const span = ( minIndex - cell[ mode ] ) + Math.max( 0, cell[ mode ] + cell.node.getSpans()[ mode ] - 1 - maxIndex );
831 let data;
832 if ( mode === 'row' ) {
833 data = { rowspan: span };
834 } else {
835 data = { colspan: span };
836 }
837
838 const surfaceModel = this.surface.getModel();
839 return ve.dm.TransactionBuilder.static.newFromAttributeChanges.bind( null, surfaceModel.getDocument(), cell.node.getOuterRange().start, data );
840 };
841
842 /**
843 * Deletes rows or columns within a given range.
844 *
845 * e.g. rows 2-4 can be deleted using
846 *
847 * ve.ui.TableAction.deleteRowsOrColumns( matrix, 'row', 1, 3 );
848 *
849 * @param {ve.dm.TableMatrix} matrix Table matrix
850 * @param {string} mode 'row' or 'col'
851 * @param {number} minIndex Smallest row or column index to be deleted
852 * @param {number} maxIndex Largest row or column index to be deleted (inclusive)
853 * @return {Object[]} Plain sub-matrix of items removed. In column mode this matrix is transposed.
854 */
855 ve.ui.TableAction.prototype.deleteRowsOrColumns = function ( matrix, mode, minIndex, maxIndex ) {
856 const removedMatrix = [],
857 txBuilders = [],
858 adapted = {},
859 actions = [],
860 cells = [],
861 surfaceModel = this.surface.getModel(),
862 documentModel = surfaceModel.getDocument();
863
864 // Deleting cells can have two additional consequences:
865 // 1. The cell is a Placeholder. The owner's span must be decreased.
866 // 2. The cell is owner of placeholders which get orphaned by the deletion.
867 // The first of the placeholders now becomes the real cell, with the span adjusted.
868 // It also inherits all of the properties and content of the removed cell.
869 // Insertions and deletions of cells must be done in an appropriate order, so that the transactions
870 // do not interfere with each other. To achieve that, we record insertions and deletions and
871 // sort them by the position of the cell (row, column) in the table matrix.
872
873 if ( mode === 'row' ) {
874 for ( let row = minIndex; row <= maxIndex; row++ ) {
875 ve.batchPush( cells, matrix.getRow( row ) );
876 }
877 } else {
878 for ( let col = minIndex; col <= maxIndex; col++ ) {
879 ve.batchPush( cells, matrix.getColumn( col ) );
880 }
881 }
882
883 for ( let i = 0, l = cells.length; i < l; i++ ) {
884 const cell = cells[ i ];
885 if ( !cell ) {
886 continue;
887 }
888 if ( cell.isPlaceholder() ) {
889 const key = cell.owner.key;
890 if ( !adapted[ key ] ) {
891 // Note: we can record this transaction immediately, as it does not have an effect on the
892 // node range
893 txBuilders.push( this.decrementSpan( cell.owner, mode, minIndex, maxIndex ) );
894 adapted[ key ] = true;
895 }
896 continue;
897 }
898
899 // Detect if the owner of a spanning cell gets deleted and
900 // leaves orphaned placeholders
901 const span = cell.node.getSpans()[ mode ];
902 if ( cell[ mode ] + span - 1 > maxIndex ) {
903 let startRow, startCol;
904 // add inserts for orphaned place holders
905 if ( mode === 'col' ) {
906 startRow = cell.row;
907 startCol = maxIndex + 1;
908 } else {
909 startRow = maxIndex + 1;
910 startCol = cell.col;
911 }
912 const endRow = cell.row + cell.node.getRowspan() - 1;
913 const endCol = cell.col + cell.node.getColspan() - 1;
914
915 // Record the insertion to apply it later
916 actions.push( {
917 action: 'insert',
918 cell: matrix.getCell( startRow, startCol ),
919 colspan: 1 + endCol - startCol,
920 rowspan: 1 + endRow - startRow,
921 style: cell.node.getStyle(),
922 content: documentModel.getData( cell.node.getRange() )
923 } );
924 }
925
926 // Cell nodes only get deleted when deleting columns (otherwise row nodes)
927 if ( mode === 'col' ) {
928 actions.push( { action: 'delete', cell: cell } );
929 }
930 }
931
932 // Make sure that the actions are in descending offset order
933 // so that the transactions do not affect subsequent range offsets.
934 // Sort recorded actions to make sure the transactions will not interfere with respect to offsets
935 actions.sort( ( a, b ) => ve.dm.TableMatrixCell.static.sortDescending( a.cell, b.cell ) );
936
937 if ( mode === 'row' ) {
938 // First replace orphaned placeholders which are below the last deleted row,
939 // thus, this works with regard to transaction offsets
940 for ( let i = 0; i < actions.length; i++ ) {
941 txBuilders.push( this.replacePlaceholder( matrix, actions[ i ].cell, actions[ i ] ) );
942 }
943 // Remove rows in reverse order to have valid transaction offsets
944 for ( let row = maxIndex; row >= minIndex; row-- ) {
945 const rowNode = matrix.getRowNode( row );
946 if ( !rowNode ) {
947 continue;
948 }
949 txBuilders.push( ve.dm.TransactionBuilder.static.newFromRemoval.bind( null, documentModel, rowNode.getOuterRange() ) );
950
951 // Store removed data for moving
952 const removedCells = matrix.getRow( row );
953 const rowRange = rowNode.getOuterRange();
954 const rowData = documentModel.getData( new ve.Range( rowRange.start, rowRange.start + 1 ), true ).concat(
955 documentModel.getData( new ve.Range( rowRange.end - 1, rowRange.end ), true )
956 );
957 // Remove all but start and end tags
958 rowData.splice( 1, rowData.length - 2 );
959 removedMatrix[ row - minIndex ] = {
960 row: rowData,
961 cells: removedCells.map( ( ce ) => {
962 if ( ce && !ce.isPlaceholder() ) {
963 ce.data = documentModel.getData( ce.node.getOuterRange(), true );
964 // When re-insterted the span can not exceed the size of the selection
965 if ( ce.data[ 0 ].attributes.rowspan > 1 + maxIndex - minIndex ) {
966 ce.data = null;
967 }
968 }
969 return ce;
970 } )
971 };
972 }
973 } else {
974 for ( let i = 0; i < actions.length; i++ ) {
975 if ( actions[ i ].action === 'insert' ) {
976 txBuilders.push( this.replacePlaceholder( matrix, actions[ i ].cell, actions[ i ] ) );
977 } else {
978 txBuilders.push( ve.dm.TransactionBuilder.static.newFromRemoval.bind( null, documentModel, actions[ i ].cell.node.getOuterRange() ) );
979 actions[ i ].cell.data = documentModel.getData( actions[ i ].cell.node.getOuterRange(), true );
980 }
981 }
982 for ( let col = maxIndex; col >= minIndex; col-- ) {
983 removedMatrix[ col - minIndex ] = {
984 cells: matrix.getColumn( col ).map( ( c ) => {
985 if ( c && !c.isPlaceholder() ) {
986 c.data = documentModel.getData( c.node.getOuterRange(), true );
987 // When re-insterted the span can not exceed the size of the selection
988 if ( c.data[ 0 ].attributes.colspan > 1 + maxIndex - minIndex ) {
989 c.data = null;
990 }
991 }
992 return c;
993 } )
994 };
995 }
996 }
997 surfaceModel.change( null, new ve.dm.NullSelection() );
998 txBuilders.forEach( ( txBuilder ) => {
999 surfaceModel.change( txBuilder() );
1000 } );
1001 return removedMatrix;
1002 };
1003
1004 /**
1005 * Inserts a new cell for an orphaned placeholder.
1006 *
1007 * @param {ve.dm.TableMatrix} matrix Table matrix
1008 * @param {ve.dm.TableMatrixCell} placeholder Placeholder cell to replace
1009 * @param {Object} [options] Options to pass to ve.dm.TableCellNode.static.createData
1010 * @return {Function} Zero-argument function returning a ve.dm.Transaction
1011 */
1012 ve.ui.TableAction.prototype.replacePlaceholder = function ( matrix, placeholder, options ) {
1013 // For inserting the new cell a reference cell node
1014 // which is used to get an insertion offset.
1015 const refCell = matrix.findClosestCell( placeholder );
1016
1017 let range, offset;
1018 if ( refCell ) {
1019 range = refCell.node.getOuterRange();
1020 offset = ( placeholder.col < refCell.col ) ? range.start : range.end;
1021 } else {
1022 const rowNode = matrix.getRowNode( placeholder.row );
1023 if ( !rowNode ) {
1024 return function () {
1025 return null;
1026 };
1027 }
1028 // if there are only placeholders in the row, the row node's inner range is used
1029 range = rowNode.getRange();
1030 offset = range.start;
1031 }
1032 const data = ve.dm.TableCellNode.static.createData( options );
1033 const surfaceModel = this.surface.getModel();
1034 return ve.dm.TransactionBuilder.static.newFromInsertion.bind( null, surfaceModel.getDocument(), offset, data );
1035 };
1036
1037 /**
1038 * Find the closest table node to the current selection
1039 *
1040 * This method is model-only.
1041 *
1042 * @return {ve.dm.TableNode|null} The closest table node, null if not found
1043 */
1044 ve.ui.TableAction.prototype.findClosestTableNode = function () {
1045 const surfaceModel = this.surface.getModel(),
1046 documentModel = surfaceModel.getDocument(),
1047 selection = this.surface.getModel().getSelection();
1048
1049 if ( selection instanceof ve.dm.TableSelection ) {
1050 return selection.getTableNode( documentModel );
1051 } else if ( selection instanceof ve.dm.LinearSelection ) {
1052 const node = documentModel.getBranchNodeFromOffset( selection.getRange().start );
1053 if ( node ) {
1054 return node.findParent( ve.dm.TableNode );
1055 }
1056 }
1057
1058 return null;
1059 };
1060
1061 /**
1062 * Find the closest table view node to the current selection
1063 *
1064 * @return {ve.ce.TableNode|null} The closest table view, null if not found
1065 */
1066 ve.ui.TableAction.prototype.findClosestTableViewNode = function () {
1067 const tableNode = this.findClosestTableNode();
1068
1069 if ( tableNode ) {
1070 return this.surface.getView().getDocument().getBranchNodeFromOffset( tableNode.getRange().start );
1071 }
1072
1073 return null;
1074 };
1075
1076 /**
1077 * Get a TableSelection that contains the current selection
1078 *
1079 * This method is model-only.
1080 *
1081 * @return {ve.dm.TableSelection|null} The closest TableSelection, null if not found
1082 */
1083 ve.ui.TableAction.prototype.getTableSelectionFromSelection = function () {
1084 // If the current selection is contained within a table, we'd like the relevant TableSelection.
1085 const surfaceModel = this.surface.getModel();
1086 let selection = surfaceModel.getSelection();
1087
1088 if ( selection instanceof ve.dm.TableSelection ) {
1089 return selection;
1090 } else if ( selection instanceof ve.dm.LinearSelection ) {
1091 const tableNode = this.findClosestTableNode();
1092 if ( !tableNode ) {
1093 return null;
1094 }
1095
1096 const documentModel = surfaceModel.getDocument();
1097 const node = documentModel.getBranchNodeFromOffset( selection.getRange().start );
1098 if ( !node ) {
1099 return null;
1100 }
1101
1102 const cellNode = node.findParent( ve.dm.TableCellNode );
1103 if ( !cellNode ) {
1104 return null;
1105 }
1106
1107 const cell = tableNode.getMatrix().lookupCell( cellNode );
1108 if ( !cell ) {
1109 return null;
1110 }
1111
1112 selection = new ve.dm.TableSelection(
1113 tableNode.getOuterRange(),
1114 cell.col, cell.row
1115 );
1116 return selection.expand( documentModel );
1117 }
1118
1119 return null;
1120 };
1121
1122 /* Registration */
1123
1124 ve.ui.actionFactory.register( ve.ui.TableAction );