Cleaning up HorizontalLayout path calculations

This commit is contained in:
Jeff Avallone 2019-01-29 17:47:22 -05:00
parent b47d03cb31
commit cdb77255a7
1 changed files with 23 additions and 20 deletions

View File

@ -3,14 +3,17 @@ import PropTypes from 'prop-types';
import * as style from 'rendering/style'; import * as style from 'rendering/style';
const HorizontalLayout = ({ connectorPath, transforms, children }) => { const HorizontalLayout = ({
return <> withConnectors,
<path style={ style.connectors } d={ connectorPath }/> connectorPath,
{ React.Children.map(children, (child, i) => ( transforms,
<g transform={ transforms[i] }>{ child }</g> children
)) } }) => <>
</>; { withConnectors && <path style={ style.connectors } d={ connectorPath }/> }
}; { React.Children.map(children, (child, i) => (
<g transform={ transforms[i] }>{ child }</g>
)) }
</>;
HorizontalLayout.defaultProps = { HorizontalLayout.defaultProps = {
withConnectors: false, withConnectors: false,
@ -29,35 +32,35 @@ HorizontalLayout.propTypes = {
}; };
const generateOffsetBoxes = (boxes, axisY, spacing) => { const generateOffsetBoxes = (boxes, axisY, spacing) => {
let offset = 0; let x = 0;
return boxes.map(box => { return boxes.map(box => {
try { try {
const y = axisY - box.axisY;
return { return {
...box, ...box,
offsetX: offset, x, y,
offsetY: axisY - box.axisY axisX1: x + box.axisX1,
axisX2: x + box.axisX2,
axisY: y + box.axisY
}; };
} }
finally { finally {
offset += box.width + spacing; x += box.width + spacing;
} }
}); });
}; };
const calculateChildTransforms = boxes => const calculateChildTransforms = boxes =>
boxes.map(box => `translate(${ box.offsetX } ${ box.offsetY })`); boxes.map(box => `translate(${ box.x } ${ box.y })`);
const calculateConnectorPath = (boxes, axisY) => { const calculateConnectorPath = boxes => {
let last = boxes[0]; let last = boxes[0];
return boxes.slice(1).map(box => { return boxes.slice(1).map(box => {
try { try {
return ` return `M${ last.axisX2 },${ box.axisY } H${ box.axisX1 }`;
M${ last.offsetX + last.axisX2 },${ axisY }
H${ box.offsetX + box.axisX1 }
`;
} }
finally { finally {
last = box; last = box;
} }
}).join(''); }).join('\n');
}; };
const layout = data => { const layout = data => {
const { withConnectors, spacing } = { const { withConnectors, spacing } = {
@ -79,7 +82,7 @@ const layout = data => {
...data.props, ...data.props,
transforms: calculateChildTransforms(offsetBoxes), transforms: calculateChildTransforms(offsetBoxes),
connectorPath: withConnectors connectorPath: withConnectors
? calculateConnectorPath(offsetBoxes, data.box.axisY) ? calculateConnectorPath(offsetBoxes)
: undefined : undefined
}; };