This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
inserttablecommand.js
77 lines (64 loc) · 2.3 KB
/
inserttablecommand.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md.
*/
/**
* @module table/commands/inserttablecommand
*/
import Command from '@ckeditor/ckeditor5-core/src/command';
import Position from '@ckeditor/ckeditor5-engine/src/model/position';
import TableUtils from '../tableutils';
/**
* The insert table command.
*
* The command is registered by {@link module:table/tableediting~TableEditing} as `'insertTable'` editor command.
*
* To insert a table at the current selection, execute the command and specify the dimensions:
*
* editor.execute( 'insertTable', { rows: 20, columns: 5 } );
*
* @extends module:core/command~Command
*/
export default class InsertTableCommand extends Command {
/**
* @inheritDoc
*/
refresh() {
const model = this.editor.model;
const selection = model.document.selection;
const schema = model.schema;
const validParent = getInsertTableParent( selection.getFirstPosition() );
this.isEnabled = schema.checkChild( validParent, 'table' );
}
/**
* Executes the command.
*
* Inserts a table with the given number of rows and columns into the editor.
*
* @param {Object} options
* @param {Number} [options.rows=2] The number of rows to create in the inserted table.
* @param {Number} [options.columns=2] The number of columns to create in the inserted table.
* @fires execute
*/
execute( options = {} ) {
const model = this.editor.model;
const selection = model.document.selection;
const tableUtils = this.editor.plugins.get( TableUtils );
const rows = parseInt( options.rows ) || 2;
const columns = parseInt( options.columns ) || 2;
const firstPosition = selection.getFirstPosition();
const isRoot = firstPosition.parent === firstPosition.root;
const insertPosition = isRoot ? Position.createAt( firstPosition ) : Position.createAfter( firstPosition.parent );
model.change( writer => {
const table = tableUtils.createTable( insertPosition, rows, columns );
writer.setSelection( Position.createAt( table.getChild( 0 ).getChild( 0 ) ) );
} );
}
}
// Returns valid parent to insert table
//
// @param {module:engine/model/position} position
function getInsertTableParent( position ) {
const parent = position.parent;
return parent === parent.root ? parent : parent.parent;
}