Created
January 4, 2020 18:54
-
-
Save prevwong/8471d1406836753032f344421dfce707 to your computer and use it in GitHub Desktop.
A simple Grid layout system with Craft.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get total `width` of all children | |
const getAccumulatedChildrenWidth = (helper, parentId) => { | |
return helper(self.id).decendants().map(id => helper(id).get()) | |
.reduce((a, b) => a.data.props.width + b.data.props.width, 0); | |
} | |
const Grid = () => { | |
return ( | |
<div> | |
{children} | |
</div> | |
) | |
} | |
// 1. Add a rule to reject any more GridItem if there is no more space on the Grid | |
Grid.craft = { | |
canMoveIn = (node, self, helper) => node.data.type == GridItem && getAccumulatedChildrenWidth(helper, self.id) <= 12; | |
} | |
export const GridItem = ({width = 2, children}) => { | |
const isNew = useRef(true); | |
const { parentId, setProp } = useNode((node) => ({ | |
parentId: node.id | |
})); | |
/** 2. | |
* If the GridItem is rendered with a `width` that is more than the remaining space on the Grid, | |
* then, resize the GridItem to fit the remaining space | |
*/ | |
useManager((_, query) => { | |
const accumulatedChildrenWidth = getAccumulatedChildrenWidth(query.node, parentId); | |
const remainingWidth = 12 - accumulatedChildrenWidth; | |
if ( isNew.current && width > remainingWidth ) { | |
setProp(props => props.width = remainingWidth); | |
isNew.current = false; | |
} | |
}); | |
return ( | |
<div className={`md-${width}`}> | |
{children} | |
</div> | |
) | |
} | |
i'm strugling a lot to make grids because i'm using Ant Design and it should use his grid components...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@danielcranney I did not work on this so nothing to report from my end. Sorry.