Skip to content

Commit dfe4c3b

Browse files
committed
Compact word wrap (partial)
1 parent 06c3d49 commit dfe4c3b

File tree

3 files changed

+35
-3
lines changed

3 files changed

+35
-3
lines changed

src/cell.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ class Cell {
6767
i++;
6868
}
6969
}
70-
this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content));
70+
this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content, tableOptions.wrapWords));
7171
} else {
7272
this.lines = utils.colorizeLines(this.content.split('\n'));
7373
}

src/utils.js

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,11 +271,31 @@ function wordWrap(maxLength, input) {
271271
return lines;
272272
}
273273

274-
function multiLineWordWrap(maxLength, input) {
274+
function wrapWords(maxLength, input) {
275+
let lines = [];
276+
let line = '';
277+
function pushLine(str, ws) {
278+
if (line.length && ws) line += ws;
279+
line += str;
280+
while (line.length > maxLength) {
281+
lines.push(line.slice(0, maxLength));
282+
line = line.slice(maxLength);
283+
}
284+
}
285+
let split = input.split(/(\s+)/g);
286+
for (let i = 0; i < split.length; i += 2) {
287+
pushLine(split[i], i && split[i - 1]);
288+
}
289+
if (line.length) lines.push(line);
290+
return lines;
291+
}
292+
293+
function multiLineWordWrap(maxLength, input, words = false) {
275294
let output = [];
276295
input = input.split('\n');
296+
const handler = words ? wrapWords : wordWrap;
277297
for (let i = 0; i < input.length; i++) {
278-
output.push.apply(output, wordWrap(maxLength, input[i]));
298+
output.push.apply(output, handler(maxLength, input[i]));
279299
}
280300
return output;
281301
}

test/utils-test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,18 @@ describe('utils', function () {
322322
let expected = ['\x1b[31m漢字\x1b[0m', ' 漢字'];
323323
expect(wordWrap(5, input)).toEqual(expected);
324324
});
325+
326+
describe('wrapWords', function () {
327+
it('wraps long words', function () {
328+
expect(wordWrap(10, 'abcdefghijklmnopqrstuvwxyz', true)).toEqual(['abcdefghij', 'klmnopqrst', 'uvwxyz']);
329+
expect(wordWrap(10, 'abcdefghijk lmnopqrstuv wxyz', true)).toEqual(['abcdefghij', 'k lmnopqrs', 'tuv wxyz']);
330+
expect(wordWrap(10, 'ab cdefghijk lmnopqrstuv wx yz', true)).toEqual([
331+
'ab cdefghi',
332+
'jk lmnopqr',
333+
'stuv wx yz',
334+
]);
335+
});
336+
});
325337
});
326338

327339
describe('colorizeLines', function () {

0 commit comments

Comments
 (0)