Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sweeping performance improvements and onload resizing #27

Merged
merged 2 commits into from Jan 5, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
53 changes: 38 additions & 15 deletions lib/ReactFitText.js
Expand Up @@ -14,14 +14,39 @@ var ReactDOM = require('react-dom');
var ReactPropTypes = require('prop-types');
var createClass = require('create-react-class');

// Map from node to options
const nodes = new Map();

function updateElementStyle(element, options, width) {
element.style.fontSize = `${Math.min(Math.max(width / (options.compressor * 10), options.minFontSize), options.maxFontSize)}px`;
}

let updateQueued = false;

function onBodyResize() {
updateQueued = true;
const widths = [];
nodes.forEach((options, element) => {
widths.push(element.offsetWidth);
});
let i = 0;
nodes.forEach((options, element) => {
updateElementStyle(element, options, widths[i]);
i += 1;
});
}

window.addEventListener("resize", onBodyResize);
window.addEventListener("load", onBodyResize);

module.exports = createClass({
displayName: 'ReactFitText',

propTypes: {
children: ReactPropTypes.element.isRequired,
compressor: ReactPropTypes.number,
minFontSize: ReactPropTypes.number,
maxFontSize: ReactPropTypes.number
maxFontSize: ReactPropTypes.number,
},

getDefaultProps: function() {
Expand All @@ -32,33 +57,31 @@ module.exports = createClass({
};
},

componentDidMount: function() {
window.addEventListener("resize", this._onBodyResize);
this._onBodyResize();
componentWillMount: function() {
if (!updateQueued) {
window.requestAnimationFrame(onBodyResize);
}
},

componentWillUnmount: function() {
window.removeEventListener("resize", this._onBodyResize);
if (this._childRef) {
nodes.delete(this._childRef);
}
},

componentDidUpdate: function() {
this._onBodyResize();
onBodyResize();
},

_onBodyResize: function() {
var element = ReactDOM.findDOMNode(this);
var width = element.offsetWidth;
element.style.fontSize = Math.max(
Math.min((width / (this.props.compressor*10)),
parseFloat(this.props.maxFontSize)),
parseFloat(this.props.minFontSize)) + 'px';
},
_renderChildren: function(){
var _this = this;

return React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, { ref: function ref(c) {
return _this._childRef = c;
if (c) {
nodes.set(c, _this.props);
}
_this._childRef = c;
} });
});
},
Expand Down