Skip to content

Commit

Permalink
update(alloc): return with target element and allocated fontSize
Browse files Browse the repository at this point in the history
  • Loading branch information
idiotWu committed Sep 28, 2016
1 parent 21f9aca commit ccb6fcb
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@
return el.currentStyle[prop];
}

function getWidth(el) {
var bound = el.getBoundingClientRect();

return bound.width || (bound.right - bound.left);
};

function forEach(arr, fn) {
if (typeof arr.forEach === 'function') {
return arr.forEach(fn);
Expand Down Expand Up @@ -134,12 +140,16 @@
}
};

FlexText.prototype.clear = function clear() {
this.items.length = 0;
};

FlexText.prototype.alloc = function alloc() {
var items = this.items;
var spacing = this.spacing;
var container = this.container;

var totalSpace = container.clientWidth;
var totalSpace = getWidth(container);

var widths = [];
var totalWidth = 0;
Expand All @@ -163,7 +173,7 @@

span.textContent = span.innerText = text;

var width = span.clientWidth;
var width = getWidth(span);

widths.push(width);
totalWidth += width;
Expand All @@ -172,12 +182,15 @@
totalSpace -= parseFloat(spacing) * whiteSpaceCount;

return map(widths, function (w, i) {
var flex = items[i].flex;
var item = items[i];

var fontSize = BASE_FONT_SIZE * flex;
var fontSize = BASE_FONT_SIZE * item.flex;
var targetWidth = (w / totalWidth) * totalSpace;

return Math.max(0, fontSize / (w / targetWidth));
return {
elem: item.elem,
fontSize: Math.max(0, fontSize / (w / targetWidth)),
};
});
};

Expand All @@ -186,10 +199,11 @@

var result = this.alloc();

forEach(this.items, function (item, idx) {
forEach(result, function (item, idx) {
var elem = item.elem;
var fontSize = item.fontSize;

elem.style.fontSize = Math.floor(result[idx]) + 'px';
elem.style.fontSize = Math.floor(fontSize) + 'px';

if (idx > 0) {
elem.style.marginLeft = spacing + 'px';
Expand Down

0 comments on commit ccb6fcb

Please sign in to comment.