-
Notifications
You must be signed in to change notification settings - Fork 1
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
Add the WpBlock
custom element
#39
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
/** | ||
* External dependencies | ||
*/ | ||
import { hydrate as ReactHydrate } from 'react-dom'; | ||
import { ReactElement } from 'react'; | ||
|
||
type HydrateOptions = { | ||
technique?: 'media' | 'view' | 'idle'; | ||
media?: string; | ||
}; | ||
|
||
export const hydrate = ( | ||
element: ReactElement, | ||
container: Element, | ||
hydrationOptions: HydrateOptions = {} | ||
) => { | ||
const { technique, media } = hydrationOptions; | ||
const cb = () => { | ||
ReactHydrate( element, container ); | ||
}; | ||
switch ( technique ) { | ||
case 'media': | ||
if ( media ) { | ||
const mql = matchMedia( media ); | ||
if ( mql.matches ) { | ||
cb(); | ||
} else { | ||
mql.addEventListener( 'change', cb, { once: true } ); | ||
} | ||
} | ||
break; | ||
// Hydrate the element when is visible in the viewport. | ||
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API | ||
case 'view': | ||
try { | ||
const io = new IntersectionObserver( ( entries ) => { | ||
for ( const entry of entries ) { | ||
if ( ! entry.isIntersecting ) { | ||
continue; | ||
} | ||
// As soon as we hydrate, disconnect this IntersectionObserver. | ||
io.disconnect(); | ||
cb(); | ||
break; // break loop on first match | ||
} | ||
} ); | ||
io.observe( container.children[ 0 ] ); | ||
} catch ( e ) { | ||
cb(); | ||
} | ||
break; | ||
case 'idle': | ||
// Safari does not support requestIdleCalback, we use a timeout instead. https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback | ||
if ( 'requestIdleCallback' in window ) { | ||
window.requestIdleCallback( cb ); | ||
} else { | ||
setTimeout( cb, 200 ); | ||
} | ||
break; | ||
// Hydrate this component immediately. | ||
default: | ||
cb(); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
/** | ||
* External dependencies | ||
*/ | ||
import { ReactElement } from 'react'; | ||
|
||
/** | ||
* Internal dependencies | ||
*/ | ||
import { matcherFromSource, pickKeys } from './utils'; | ||
import { hydrate } from './bhe-element'; | ||
|
||
declare global { | ||
interface Window { | ||
blockTypes: Map< string, ReactElement >; | ||
} | ||
} | ||
|
||
declare global { | ||
// eslint-disable-next-line @typescript-eslint/no-namespace, @typescript-eslint/no-unused-vars | ||
namespace JSX { | ||
interface IntrinsicElements { | ||
// eslint-disable-next-line @typescript-eslint/naming-convention | ||
'gutenberg-inner-blocks': React.DetailedHTMLProps< | ||
React.HTMLAttributes< HTMLElement >, | ||
HTMLElement | ||
>; | ||
} | ||
} | ||
} | ||
|
||
// We assign `blockTypes` to window to make sure it's a global singleton. | ||
// | ||
// Have to do this because of the way we are currently bundling the code | ||
// in this repo, each block gets its own copy of this file. | ||
// | ||
// We COULD fix this by doing some webpack magic to spit out the code in | ||
// `gutenberg-packages` to a shared chunk but assigning `blockTypes` to window | ||
// is a cheap hack for now that will be fixed once we can merge this code into Gutenberg. | ||
if ( typeof window.blockTypes === 'undefined' ) { | ||
window.blockTypes = new Map(); | ||
} | ||
|
||
export const registerBlockType = ( name: string, Comp: ReactElement ) => { | ||
window.blockTypes.set( name, Comp ); | ||
}; | ||
|
||
const Children = ( { value, providedContext } ) => { | ||
if ( ! value ) { | ||
return null; | ||
} | ||
return ( | ||
<gutenberg-inner-blocks | ||
ref={ ( el ) => { | ||
if ( el !== null ) { | ||
// listen for the ping from the child | ||
el.addEventListener( 'gutenberg-context', ( event ) => { | ||
// We have to also destructure `event.detail.context` because there can | ||
// already exist a property in the context with the same name. | ||
event.detail.context = { | ||
...providedContext, | ||
...event?.detail?.context, | ||
}; | ||
} ); | ||
} | ||
} } | ||
suppressHydrationWarning={ true } | ||
dangerouslySetInnerHTML={ { __html: value } } | ||
/> | ||
); | ||
}; | ||
Children.shouldComponentUpdate = () => false; | ||
|
||
class GutenbergBlock extends HTMLElement { | ||
connectedCallback() { | ||
setTimeout( () => { | ||
// ping the parent for the context | ||
const event = new CustomEvent( 'gutenberg-context', { | ||
detail: {}, | ||
bubbles: true, | ||
cancelable: true, | ||
} ); | ||
this.dispatchEvent( event ); | ||
|
||
const usesContext = JSON.parse( | ||
this.getAttribute( 'data-gutenberg-context-used' ) as string | ||
); | ||
const providesContext = JSON.parse( | ||
this.getAttribute( 'data-gutenberg-context-provided' ) as string | ||
); | ||
const attributes = JSON.parse( | ||
this.getAttribute( 'data-gutenberg-attributes' ) as string | ||
); | ||
const sourcedAttributes = JSON.parse( | ||
this.getAttribute( | ||
'data-gutenberg-sourced-attributes' | ||
) as string | ||
); | ||
|
||
for ( const attr in sourcedAttributes ) { | ||
attributes[ attr ] = matcherFromSource( | ||
sourcedAttributes[ attr ] | ||
)( this ); | ||
} | ||
|
||
// pass the context to children if needed | ||
const providedContext = | ||
providesContext && | ||
pickKeys( attributes, Object.keys( providesContext ) ); | ||
|
||
// select only the parts of the context that the block declared in | ||
// the `usesContext` of its block.json | ||
const context = pickKeys( event.detail.context, usesContext ); | ||
|
||
const blockType = this.getAttribute( 'data-gutenberg-block-type' ); | ||
const blockProps = { | ||
className: this.children[ 0 ].className, | ||
style: this.children[ 0 ].style, | ||
}; | ||
|
||
const innerBlocks = this.querySelector( | ||
'template.gutenberg-inner-blocks' | ||
); | ||
const Comp = window.blockTypes.get( blockType ); | ||
const technique = this.getAttribute( 'data-gutenberg-hydrate' ); | ||
const media = this.getAttribute( 'data-gutenberg-media' ); | ||
const hydrationOptions = { technique, media }; | ||
hydrate( | ||
<> | ||
<Comp | ||
attributes={ attributes } | ||
blockProps={ blockProps } | ||
suppressHydrationWarning={ true } | ||
context={ context } | ||
> | ||
<Children | ||
value={ innerBlocks && innerBlocks.innerHTML } | ||
suppressHydrationWarning={ true } | ||
providedContext={ providedContext } | ||
/> | ||
</Comp> | ||
<template | ||
className="gutenberg-inner-blocks" | ||
suppressHydrationWarning={ true } | ||
/> | ||
</>, | ||
this, | ||
hydrationOptions | ||
); | ||
} ); | ||
} | ||
} | ||
|
||
// We need to wrap the element registration code in a conditional for the same | ||
// reason we assing `blockTypes` to window (see top of the file). | ||
// | ||
// We need to ensure that the component registration code is only run once | ||
// because it throws if you try to register an element with the same name twice. | ||
if ( customElements.get( 'gutenberg-interactive-block' ) === undefined ) { | ||
customElements.define( 'gutenberg-interactive-block', GutenbergBlock ); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/** | ||
* External dependencies | ||
*/ | ||
import { text } from 'hpq'; | ||
|
||
/** | ||
* Pick the keys of an object that are present in the provided array. | ||
* | ||
* @param {Object} obj | ||
* @param {Array} arr | ||
*/ | ||
export const pickKeys = ( obj, arr ) => { | ||
if ( obj === undefined ) { | ||
return; | ||
} | ||
|
||
const result = {}; | ||
for ( const key of arr ) { | ||
if ( obj[ key ] !== undefined ) { | ||
result[ key ] = obj[ key ]; | ||
} | ||
} | ||
return result; | ||
}; | ||
|
||
// See https://github.com/WordPress/gutenberg/blob/trunk/packages/blocks/src/api/parser/get-block-attributes.js#L185 | ||
export const matcherFromSource = ( sourceConfig ) => { | ||
switch ( sourceConfig.source ) { | ||
// TODO: Add cases for other source types. | ||
case 'text': | ||
return text( sourceConfig.selector ); | ||
} | ||
}; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should probably also update the "nomenclature" here, see #21 (comment) 🙂
(tl;dr
gutenberg
➡️wp
, orwp-block
in other contexts)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've taken the liberty of applying some nomenclature fixes in f7b465b. Feel free to revert if you don't like them! 😄
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @ockham ! I was going to do the same thing but you beat me to it :)