Skip to content

Commit ff04aaf

Browse files
Added UI.splitText util
1 parent d5f8c93 commit ff04aaf

File tree

2 files changed

+54
-3
lines changed

2 files changed

+54
-3
lines changed

src/UI.mjs

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import Blessed from "@farjs/blessed";
2-
31
/**
4-
* @typedef { import('blessed').Widgets.Types.TStyle } BlessedStyle
2+
* @typedef { import("@farjs/blessed").Widgets.Types.TStyle } BlessedStyle
53
*/
4+
import Blessed from "@farjs/blessed";
65

76
/**
87
* @param {BlessedStyle | undefined} style
@@ -33,3 +32,34 @@ export function renderText(isBold, fgColor, bgColor, text) {
3332
const bold = isBold ? "{bold}" : "";
3433
return `${bold}{${fgColor}-fg}{${bgColor}-bg}${Blessed.escape(text)}{/}`;
3534
}
35+
36+
/**
37+
* @param {string} text
38+
* @param {number} maxLen
39+
* @returns {string[]}
40+
*/
41+
export function splitText(text, maxLen) {
42+
const sentences = text.split("\n");
43+
44+
return sentences.flatMap((sentence) => {
45+
const words = sentence.trim().split(" ");
46+
const res = /** @type {string[]} */ ([]);
47+
48+
words.forEach((item) => {
49+
if (res.length === 0) {
50+
res.push(item);
51+
return;
52+
}
53+
54+
const hIndex = res.length - 1;
55+
const head = res[hIndex];
56+
if (head.length + item.length >= maxLen) {
57+
res.push(item);
58+
} else {
59+
res[hIndex] = `${head} ${item}`;
60+
}
61+
});
62+
63+
return res;
64+
});
65+
}

test/UI.test.mjs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,25 @@ describe("UI.test.mjs", () => {
8484
//then
8585
assert.deepEqual(result, "{yellow-fg}{blue-bg}start/-{open}{close}end{/}");
8686
});
87+
88+
it("should split text when splitText", () => {
89+
//when & then
90+
assert.deepEqual(UI.splitText("", 2), [""]);
91+
assert.deepEqual(UI.splitText("test", 2), ["test"]);
92+
assert.deepEqual(UI.splitText("test1, test2", 11), ["test1,", "test2"]);
93+
assert.deepEqual(UI.splitText("test1, test2", 12), ["test1, test2"]);
94+
assert.deepEqual(UI.splitText("test1, test2, test3", 12), [
95+
"test1,",
96+
"test2, test3",
97+
]);
98+
assert.deepEqual(UI.splitText("test1, test2, test3", 13), [
99+
"test1, test2,",
100+
"test3",
101+
]);
102+
assert.deepEqual(UI.splitText("test1, \n\n test2, test3", 13), [
103+
"test1,",
104+
"",
105+
"test2, test3",
106+
]);
107+
});
87108
});

0 commit comments

Comments
 (0)