Skip to content

Instantly share code, notes, and snippets.

@amirouche
Last active August 29, 2015 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amirouche/c756a6bb4de2aa95e958 to your computer and use it in GitHub Desktop.
Save amirouche/c756a6bb4de2aa95e958 to your computer and use it in GitHub Desktop.
facebook css-layout example
/* layout debug */
[].forEach.call(
document.querySelectorAll("*"),
function(a){
a.style.outline="1px solid hsl(" + Math.random() * 360 +", 70%, 70%)";
}
)
function elementToLayoutTree(element){
var out = {element: element};
var style = element.getAttribute("layout");
if(style) {
out.style = JSON.parse(style);
}
// uncomment to make it work
// if(!styles) {
// out.style = {};
// }
out.children = Array.slice(element.children).map(elementToLayoutTree);
return out;
}
var wrapper = document.getElementById('wrapper')
var tree = elementToLayoutTree(wrapper);
console.log(tree);
/* css-layout magic is done here
tree is modified in place */
computeLayout(tree);
function applyLayout(tree) {
tree.element.style.position = "absolute";
['top', 'left', 'width', 'height'].forEach(function(property) {
tree.element.style[property] = tree.layout[property] + 'px';
});
tree.children.forEach(applyLayout);
}
applyLayout(tree);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" media="all" rel="stylesheet" type="text/css" />
<title>css-layout foobar</title>
</head>
<body>
<div layout='{"padding": 10, "flex": "row"}' id="wrapper">
<!-- notice the layout attribute -->
<div layout='{"alignSelf": "stretch", "width": 100, "height": 100}'></div>
<div layout='{"alignSelf": "stretch", "width": 100, "height": 100}'></div>
<div>no layout attribute !</div>
</div>
<script src="src/Layout.js"></script>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment