Skip to content
This repository has been archived by the owner on Oct 16, 2024. It is now read-only.

Commit

Permalink
Merge pull request #115 from studiopress/try/force-rerender-all-stale…
Browse files Browse the repository at this point in the history
…-previews

Fix preview width when searching or filtering patterns
  • Loading branch information
mike-day authored Mar 15, 2023
2 parents 8d94f4a + 7618669 commit 5f5efb7
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 20 deletions.
6 changes: 2 additions & 4 deletions wp-modules/app/js/src/components/Patterns/PatternGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import loadable from '@loadable/component';
import { patternManager } from '../../globals';

// Hooks
import useWindowResize from '../../hooks/useWindowResize';
import useForceRerender from '../../hooks/useForceRerender';

// Components
const PatternPreview: PatternPreviewType = loadable(
Expand All @@ -29,9 +29,7 @@ type Props = {

/** Render the patterns in a grid, or a message if no patterns are found. */
export default function PatternGrid( { themePatterns }: Props ) {
// If the window is resized, trigger a fresh render of the grid.
// Helps ensure PatternPreview iFrames are the right size.
useWindowResize();
useForceRerender( [ themePatterns ] );

return (
<>
Expand Down
22 changes: 22 additions & 0 deletions wp-modules/app/js/src/hooks/useForceRerender.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { useLayoutEffect, useState } from '@wordpress/element';

type WindowDimensions = [ number, number ];

/** Re-render the calling component when the window is resized or dependencies update. */
export default function useForceRerender< T extends unknown >(
dependencies: T[]
) {
const [ , setForceUpdate ] = useState< T[] | WindowDimensions >();

useLayoutEffect( () => {
setForceUpdate( dependencies );

function updateSizeAndRerender() {
setForceUpdate( [ window.innerWidth, window.innerHeight ] );
}

window.addEventListener( 'resize', updateSizeAndRerender );
return () =>
window.removeEventListener( 'resize', updateSizeAndRerender );
}, [ ...dependencies ] );
}
16 changes: 0 additions & 16 deletions wp-modules/app/js/src/hooks/useWindowResize.ts

This file was deleted.

0 comments on commit 5f5efb7

Please sign in to comment.