Skip to content

Commit

Permalink
Grid interactivity: Improve how grid resizer handles 0-width and 0-he…
Browse files Browse the repository at this point in the history
…ight cells
  • Loading branch information
noisysocks committed May 7, 2024
1 parent 7b221c0 commit 3c110e8
Showing 1 changed file with 38 additions and 30 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,54 +45,62 @@ export function GridItemResizer( { clientId, onChange } ) {
const rowGap = parseFloat(
getComputedCSS( gridElement, 'row-gap' )
);
const gridColumnLines = getGridLines(
const gridColumnTracks = getGridTracks(
getComputedCSS( gridElement, 'grid-template-columns' ),
columnGap
);
const gridRowLines = getGridLines(
const gridRowTracks = getGridTracks(
getComputedCSS( gridElement, 'grid-template-rows' ),
rowGap
);
const columnStart = getClosestLine(
gridColumnLines,
blockElement.offsetLeft
);
const rowStart = getClosestLine(
gridRowLines,
blockElement.offsetTop
);
const columnEnd = getClosestLine(
gridColumnLines,
blockElement.offsetLeft + boxElement.offsetWidth
);
const rowEnd = getClosestLine(
gridRowLines,
blockElement.offsetTop + boxElement.offsetHeight
);
const columnStart =
getClosestTrack(
gridColumnTracks,
blockElement.offsetLeft
) + 1;
const rowStart =
getClosestTrack(
gridRowTracks,
blockElement.offsetTop
) + 1;
const columnEnd =
getClosestTrack(
gridColumnTracks,
blockElement.offsetLeft + boxElement.offsetWidth,
'end'
) + 1;
const rowEnd =
getClosestTrack(
gridRowTracks,
blockElement.offsetTop + boxElement.offsetHeight,
'end'
) + 1;
onChange( {
columnSpan: Math.max( columnEnd - columnStart, 1 ),
rowSpan: Math.max( rowEnd - rowStart, 1 ),
columnSpan: columnEnd - columnStart + 1,
rowSpan: rowEnd - rowStart + 1,
} );
} }
/>
</BlockPopoverCover>
);
}

function getGridLines( template, gap ) {
const lines = [ 0 ];
function getGridTracks( template, gap ) {
const tracks = [];
for ( const size of template.split( ' ' ) ) {
const line = parseFloat( size );
lines.push( lines[ lines.length - 1 ] + line + gap );
const previousTrack = tracks[ tracks.length - 1 ];
const start = previousTrack ? previousTrack.end + gap : 0;
const end = start + parseFloat( size );
tracks.push( { start, end } );
}
return lines;
return tracks;
}

function getClosestLine( lines, position ) {
return lines.reduce(
( closest, line, index ) =>
Math.abs( line - position ) <
Math.abs( lines[ closest ] - position )
function getClosestTrack( tracks, position, edge = 'start' ) {
return tracks.reduce(
( closest, track, index ) =>
Math.abs( track[ edge ] - position ) <
Math.abs( tracks[ closest ][ edge ] - position )
? index
: closest,
0
Expand Down

0 comments on commit 3c110e8

Please sign in to comment.