Files
yoga/src/Layout.js

74 lines
1.6 KiB
JavaScript
Raw Normal View History

2014-03-30 17:12:38 -07:00
function computeLayout(node) {
2014-03-30 19:33:24 -07:00
function fillNodes(node) {
node.layout = {
top: undefined,
left: undefined,
width: undefined,
height: undefined
};
(node.children || []).forEach(fillNodes);
}
function extractNodes(node) {
var layout = node.layout;
delete node.layout;
if (node.children) {
layout.children = node.children.map(extractNodes);
}
return layout;
}
2014-03-30 19:51:14 -07:00
function getMargin(node) {
if ('margin' in node.style) {
return node.style.margin;
}
return 0;
}
2014-03-31 11:09:33 -07:00
var pos = {
row: 'left',
column: 'top'
};
var dim = {
row: 'width',
column: 'height'
};
function layoutNode(node) {
2014-03-31 11:09:33 -07:00
var mainAxis = node.style.flexDirection === 'row' ? 'row' : 'column';
var crossAxis = mainAxis === 'row' ? 'column' : 'row';
var mainDimInStyle = dim[mainAxis] in node.style;
if (mainDimInStyle) {
node.layout[dim[mainAxis]] = node.style[dim[mainAxis]];
}
var mainPos = 0;
2014-03-30 19:33:24 -07:00
var children = [];
(node.children || []).forEach(function(child) {
child.layout[pos[mainAxis]] = mainPos;
child.layout[pos[crossAxis]] = 0;
layoutNode(child);
2014-03-31 11:09:33 -07:00
mainPos += child.layout[dim[mainAxis]] + 2 * getMargin(child);
2014-03-30 19:18:06 -07:00
});
if (!mainDimInStyle) {
node.layout[dim[mainAxis]] = mainPos;
}
node.layout[dim[crossAxis]] = node.style[dim[crossAxis]];
node.layout.top += getMargin(node);
node.layout.left += getMargin(node);
2014-03-30 19:18:06 -07:00
}
2014-03-30 19:33:24 -07:00
fillNodes(node);
node.layout.top = 0;
node.layout.left = 0;
layoutNode(node);
return extractNodes(node);
2014-03-30 17:12:38 -07:00
}