Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

History: add getLocationWithParams method #61823

Merged
merged 2 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions packages/edit-site/src/components/add-new-pattern/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@ import {
TEMPLATE_PART_POST_TYPE,
} from '../../utils/constants';

const { useHistory, useLocation } = unlock( routerPrivateApis );
const { useHistory } = unlock( routerPrivateApis );
const { CreatePatternModal, useAddPatternCategory } = unlock(
editPatternsPrivateApis
);

export default function AddNewPattern() {
const history = useHistory();
const { params } = useLocation();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally like the direct hook to retrieve the current route's params. Most routers have a similar hook. React Router has useParams for instance.

const [ showPatternModal, setShowPatternModal ] = useState( false );
const [ showTemplatePartModal, setShowTemplatePartModal ] =
useState( false );
Expand Down Expand Up @@ -141,16 +140,17 @@ export default function AddNewPattern() {
return;
}
try {
const {
params: { postType, categoryId },
} = history.getLocationWithParams();
let currentCategoryId;
// When we're not handling template parts, we should
// add or create the proper pattern category.
if ( params.postType !== TEMPLATE_PART_POST_TYPE ) {
if ( postType !== TEMPLATE_PART_POST_TYPE ) {
const currentCategory = categoryMap
.values()
.find(
( term ) => term.name === params.categoryId
);
if ( !! currentCategory ) {
.find( ( term ) => term.name === categoryId );
if ( currentCategory ) {
currentCategoryId =
currentCategory.id ||
( await findOrCreateTerm(
Expand All @@ -170,7 +170,7 @@ export default function AddNewPattern() {
// category.
if (
! currentCategoryId &&
params.categoryId !== 'my-patterns'
categoryId !== 'my-patterns'
) {
history.push( {
postType: PATTERN_TYPES.user,
Expand Down
18 changes: 11 additions & 7 deletions packages/edit-site/src/components/page-pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@ const getFormattedDate = ( dateToDisplay ) =>
);

function useView( postType ) {
const { params } = useLocation();
const { activeView = 'all', isCustom = 'false', layout } = params;
const {
params: { activeView = 'all', isCustom = 'false', layout },
} = useLocation();
const history = useHistory();
const selectedDefaultView = useMemo( () => {
const defaultView =
Expand Down Expand Up @@ -128,14 +129,15 @@ function useView( postType ) {
const setDefaultViewAndUpdateUrl = useCallback(
( viewToSet ) => {
if ( viewToSet.type !== view?.type ) {
const { params } = history.getLocationWithParams();
history.push( {
...params,
layout: viewToSet.type,
} );
}
setView( viewToSet );
},
[ params, view?.type, history ]
[ history, view?.type ]
);

if ( isCustom === 'false' ) {
Expand Down Expand Up @@ -203,19 +205,21 @@ export default function PagePages() {
const postType = 'page';
const [ view, setView ] = useView( postType );
const history = useHistory();
const { params } = useLocation();
const { isCustom = 'false' } = params;

const onSelectionChange = useCallback(
( items ) => {
if ( isCustom === 'false' && view?.type === LAYOUT_LIST ) {
const { params } = history.getLocationWithParams();
if (
( params.isCustom ?? 'false' ) === 'false' &&
view?.type === LAYOUT_LIST
) {
history.push( {
...params,
postId: items.length === 1 ? items[ 0 ].id : undefined,
} );
}
},
[ history, params, view?.type, isCustom ]
[ history, view?.type ]
);

const queryArgs = useMemo( () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,9 @@ import SidebarNavigationItem from '../sidebar-navigation-item';
import { DEFAULT_VIEWS } from './default-views';
import { unlock } from '../../lock-unlock';

const { useHistory, useLocation } = unlock( routerPrivateApis );
const { useHistory } = unlock( routerPrivateApis );

function AddNewItemModalContent( { type, setIsAdding } ) {
const {
params: { postType },
} = useLocation();
const history = useHistory();
const { saveEntityRecord } = useDispatch( coreStore );
const [ title, setTitle ] = useState( '' );
Expand Down Expand Up @@ -68,6 +65,9 @@ function AddNewItemModalContent( { type, setIsAdding } ) {
),
}
);
const {
params: { postType },
} = history.getLocationWithParams();
history.push( {
postType,
activeView: savedRecord.id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import DataViewItem from './dataview-item';
import AddNewItem from './add-new-view';
import { unlock } from '../../lock-unlock';

const { useHistory, useLocation } = unlock( routerPrivateApis );
const { useHistory } = unlock( routerPrivateApis );

const EMPTY_ARRAY = [];

Expand Down Expand Up @@ -81,9 +81,6 @@ function RenameItemModalContent( { dataviewId, currentTitle, setIsRenaming } ) {
}

function CustomDataViewItem( { dataviewId, isActive } ) {
const {
params: { postType },
} = useLocation();
const history = useHistory();
const { dataview } = useSelect(
( select ) => {
Expand Down Expand Up @@ -145,9 +142,10 @@ function CustomDataViewItem( { dataviewId, isActive } ) {
}
);
if ( isActive ) {
history.replace( {
postType,
} );
const {
params: { postType },
} = history.getLocationWithParams();
history.replace( { postType } );
}
onClose();
} }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@ const POPOVER_PROPS = {
*/
import { unlock } from '../../lock-unlock';

const { useLocation, useHistory } = unlock( routerPrivateApis );
const { useHistory } = unlock( routerPrivateApis );

export default function LeafMoreMenu( props ) {
const { params } = useLocation();
const history = useHistory();
const { block } = props;
const { clientId } = block;
Expand Down Expand Up @@ -60,6 +59,7 @@ export default function LeafMoreMenu( props ) {
attributes.type &&
history
) {
const { params } = history.getLocationWithParams();
history.push(
{
postType: attributes.type,
Expand All @@ -72,6 +72,7 @@ export default function LeafMoreMenu( props ) {
);
}
if ( name === 'core/page-list-item' && attributes.id && history ) {
const { params } = history.getLocationWithParams();
history.push(
{
postType: 'page',
Expand All @@ -84,7 +85,7 @@ export default function LeafMoreMenu( props ) {
);
}
},
[ history, params ]
[ history ]
);

return (
Expand Down
4 changes: 2 additions & 2 deletions packages/edit-site/src/utils/use-activate-theme.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
currentlyPreviewingTheme,
} from './is-previewing-theme';

const { useHistory, useLocation } = unlock( routerPrivateApis );
const { useHistory } = unlock( routerPrivateApis );

/**
* This should be refactored to use the REST API, once the REST API can activate themes.
Expand All @@ -23,7 +23,6 @@ const { useHistory, useLocation } = unlock( routerPrivateApis );
*/
export function useActivateTheme() {
const history = useHistory();
const { params } = useLocation();
const { startResolution, finishResolution } = useDispatch( coreStore );

return async () => {
Expand All @@ -38,6 +37,7 @@ export function useActivateTheme() {
finishResolution( 'activateTheme' );
// Remove the wp_theme_preview query param: we've finished activating
// the queue and are switching to normal Site Editor.
const { params } = history.getLocationWithParams();
history.replace( { ...params, wp_theme_preview: undefined } );
}
};
Expand Down
17 changes: 17 additions & 0 deletions packages/router/src/history.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,24 @@ function replace( params, state ) {
return originalHistoryReplace.call( history, { search }, state );
}

const locationMemo = new WeakMap();
function getLocationWithParams() {
const location = history.location;
let locationWithParams = locationMemo.get( location );
if ( ! locationWithParams ) {
locationWithParams = {
...location,
params: Object.fromEntries(
new URLSearchParams( location.search )
),
};
locationMemo.set( location, locationWithParams );
}
return locationWithParams;
}

history.push = push;
history.replace = replace;
history.getLocationWithParams = getLocationWithParams;

export default history;
22 changes: 4 additions & 18 deletions packages/router/src/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,11 @@ export function useHistory() {
return useContext( HistoryContext );
}

const locationCache = new Map();
function getLocationWithParams( location ) {
if ( locationCache.get( location.search ) ) {
return locationCache.get( location.search );
}
const searchParams = new URLSearchParams( location.search );
const ret = {
...location,
params: Object.fromEntries( searchParams.entries() ),
};
locationCache.clear();
locationCache.set( location.search, ret );

return ret;
}

export function RouterProvider( { children } ) {
const location = useSyncExternalStore( history.listen, () =>
getLocationWithParams( history.location )
const location = useSyncExternalStore(
history.listen,
history.getLocationWithParams,
history.getLocationWithParams
);

return (
Expand Down
Loading