Skip to content

Commit

Permalink
add reserved space to wrapLine functionality (fabricjs#4841)
Browse files Browse the repository at this point in the history
* added back reserved space

* added test
  • Loading branch information
asturur authored Mar 20, 2018
1 parent 2165841 commit 6ec2a72
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/shapes/textbox.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -295,10 +295,11 @@
* @param {Array} line The grapheme array that represent the line
* @param {Number} lineIndex
* @param {Number} desiredWidth width you want to wrap the line to
* @param {Number} reservedSpace space to remove from wrapping for custom functionalities
* @returns {Array} Array of line(s) into which the given text is wrapped
* to.
*/
_wrapLine: function(_line, lineIndex, desiredWidth) {
_wrapLine: function(_line, lineIndex, desiredWidth, reservedSpace) {
var lineWidth = 0,
graphemeLines = [],
line = [],
Expand All @@ -311,7 +312,10 @@
infixWidth = 0,
largestWordWidth = 0,
lineJustStarted = true,
additionalSpace = this._getWidthOfCharSpacing();
additionalSpace = this._getWidthOfCharSpacing(),
reservedSpace = reservedSpace || 0;

desiredWidth -= reservedSpace;
for (var i = 0; i < words.length; i++) {
// i would avoid resplitting the graphemes
word = fabric.util.string.graphemeSplit(words[i]);
Expand Down Expand Up @@ -346,8 +350,8 @@

i && graphemeLines.push(line);

if (largestWordWidth > this.dynamicMinWidth) {
this.dynamicMinWidth = largestWordWidth - additionalSpace;
if (largestWordWidth + reservedSpace > this.dynamicMinWidth) {
this.dynamicMinWidth = largestWordWidth - additionalSpace + reservedSpace;
}

return graphemeLines;
Expand Down
25 changes: 25 additions & 0 deletions test/unit/textbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,29 @@
textbox.initDimensions();
assert.equal(textbox.textLines[0], 'xa', 'first line match expectations spacing 800');
});
QUnit.test('wrapping with custom space', function(assert) {
var textbox = new fabric.Textbox('xa xb xc xd xe ya yb id', {
width: 2000,
});
var line1 = textbox._wrapLine('xa xb xc xd xe ya yb id', 0, 100, 0);
var expected1 = [
['x', 'a', ' ', 'x', 'b'],
['x', 'c', ' ', 'x', 'd'],
['x', 'e', ' ', 'y', 'a'],
['y', 'b', ' ', 'i', 'd']];
assert.deepEqual(line1, expected1, 'wrapping without reserved');
assert.deepEqual(textbox.dynamicMinWidth, 40, 'wrapping without reserved');
var line2 = textbox._wrapLine('xa xb xc xd xe ya yb id', 0, 100, 50);
var expected2 = [
['x', 'a'],
['x', 'b'],
['x', 'c'],
['x', 'd'],
['x', 'e'],
['y', 'a'],
['y', 'b'],
['i', 'd']];
assert.deepEqual(line2, expected2, 'wrapping without reserved');
assert.deepEqual(textbox.dynamicMinWidth, 90, 'wrapping without reserved');
});
})();

0 comments on commit 6ec2a72

Please sign in to comment.