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

[Proof of concept] Portals API + Navigation block #36235

Draft
wants to merge 2 commits into
base: trunk
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions packages/block-library/src/navigation/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ function( $block ) {
if ( empty( $inner_blocks ) ) {
return '';
}

$colors = block_core_navigation_build_css_colors( $attributes );
$font_sizes = block_core_navigation_build_css_font_sizes( $attributes );
$classes = array_merge(
Expand Down
55 changes: 55 additions & 0 deletions packages/block-library/src/navigation/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,58 @@ window.onload = () =>
onClose: navigationToggleModal,
openClass: 'is-menu-open',
} );

function createPortals() {
const pageLinks = document.querySelectorAll(
'nav.wp-block-navigation ul a'
);
const siteLink = document.querySelector( 'h1.wp-block-site-title a' );
const links = [ ...pageLinks, siteLink ];

for ( const el of links ) {
// Don't create the portal for the current page
if ( el.href === window.location.href ) continue;

const portal = document.createElement( 'portal' );
portal.src = el.href;
portal.hidden = true;

document.body.append( portal );

el.onclick = async ( ev ) => {
ev.preventDefault();
portal.hidden = false;

try {
await portal.activate();
} catch {
// If the portal activation fails, do a normal navigation
portal.hidden = true;
window.location.href = el.href;
}
};
}
}

if ( 'HTMLPortalElement' in window ) {
// window.portalHost would be set in a page that was opened in a portal
if ( ! window.portalHost ) {
window.addEventListener( 'DOMContentLoaded', () => {
createPortals();
} );
} else {
// We are on the portaled page, so we should wait for the portal to be
// activated before creating the portals, otherwise we would end up with
// infinitely nested portals.
window.addEventListener( 'portalactivate', () => {
createPortals();
} );
}
} else {
window.addEventListener( 'load', () => {
document.body.innerHTML = `Your browser version does not support the Portals API.
Use the latest version of Google Chrome and go to
<a href="chrome://flags/#enable-portals"> chrome://flags/#enable-portals </a> to enable them
(copy-paste the link, clicking does not work)`;
} );
}