-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
table.js
105 lines (87 loc) 路 2.23 KB
/
table.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* @fileoverview Implements Table markdown command
* @author Sungho Kim(sungho-kim@nhnent.com) FE Development Team/NHN Ent.
*/
import CommandManager from '../commandManager';
/**
* Table
* Add table markdown syntax to markdown editor
* @extends Command
* @module markdownCommands/Table
* @ignore
*/
const Table = CommandManager.command('markdown', /** @lends Table */{
name: 'Table',
/**
* Command handler
* @param {MarkdownEditor} mde MarkdownEditor instance
* @param {number} col column count
* @param {number} row row count
* @param {Array} data initial table data
*/
exec(mde, col, row, data) {
const cm = mde.getEditor();
const doc = cm.getDoc();
let table = '\n';
if (cm.getCursor().ch > 0) {
table += '\n';
}
table += makeHeader(col, data);
table += makeBody(col, row - 1, data);
doc.replaceSelection(table);
if (!data) {
cm.setCursor(cm.getCursor().line - row, 2);
}
mde.focus();
}
});
/**
* makeHeader
* make table header markdown string
* @param {number} col Column count
* @param {array} data Cell's text content
* @returns {string} markdown string
*/
function makeHeader(col, data) {
let header = '|';
let border = '|';
let index = 0;
while (col) {
if (data) {
header += ` ${data[index]} |`;
index += 1;
} else {
header += ' |';
}
border += ' --- |';
col -= 1;
}
return `${header}\n${border}\n`;
}
/**
* makeBody
* make table body markdown string
* @param {number} col column count
* @param {number} row row count
* @param {Array} data initial table data
* @returns {string} html string
*/
function makeBody(col, row, data) {
let body = '';
let index = col;
for (let irow = 0; irow < row; irow += 1) {
body += '|';
for (let icol = 0; icol < col; icol += 1) {
if (data) {
body += ` ${data[index]} |`;
index += 1;
} else {
body += ' |';
}
}
body += '\n';
}
body = body.replace(/\n$/g, '');
return body;
}
export default Table;