diff --git a/packages/layout/src/node/shouldBreak.js b/packages/layout/src/node/shouldBreak.js index 5e01cc64a..bc213314f 100644 --- a/packages/layout/src/node/shouldBreak.js +++ b/packages/layout/src/node/shouldBreak.js @@ -6,32 +6,42 @@ const getBreak = node => node.props?.break || false; const getMinPresenceAhead = node => node.props?.minPresenceAhead || 0; -const shouldBreak = (child, futureElements, height) => { - if (child.props?.fixed) return false; +const getFurthestEnd = elements => + Math.max(...elements.map(node => node.box.top + node.box.height)); - const shouldSplit = height < child.box.top + child.box.height; - const canWrap = getWrap(child); - const minPresenceAhead = getMinPresenceAhead(child); - const afterMinPresenceAhead = +const getEndOfMinPresenceAhead = child => { + return ( child.box.top + child.box.height + child.box.marginBottom + - minPresenceAhead; - const nonFixedFutureElements = futureElements.filter( - node => !node.props?.fixed, + getMinPresenceAhead(child) ); - const endOfLastFutureElement = Math.max( - ...nonFixedFutureElements.map(node => node.box.top + node.box.height), +}; + +const getEndOfPresence = (child, futureElements) => { + const afterMinPresenceAhead = getEndOfMinPresenceAhead(child); + const endOfFurthestFutureElement = getFurthestEnd( + futureElements.filter(node => !node.props?.fixed), ); - const afterPresence = Math.min(afterMinPresenceAhead, endOfLastFutureElement); - // If the child is already at the top of the page, breaking won't improve presence + return Math.min(afterMinPresenceAhead, endOfFurthestFutureElement); +}; + +const shouldBreak = (child, futureElements, height) => { + if (child.props?.fixed) return false; + + const shouldSplit = height < child.box.top + child.box.height; + const canWrap = getWrap(child); + + // Calculate the y coordinate where the desired presence of the child ends + const endOfPresence = getEndOfPresence(child, futureElements); + // If the child is already at the top of the page, breaking won't improve its presence // (as long as react-pdf does not support breaking into differently sized containers) const breakingImprovesPresence = child.box.top > child.box.marginTop; return ( getBreak(child) || (shouldSplit && !canWrap) || - (!shouldSplit && afterPresence > height && breakingImprovesPresence) + (!shouldSplit && endOfPresence > height && breakingImprovesPresence) ); };