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

Introduce wp-on-async directive as performant alternative over synchronous wp-on directive #61885

Merged
merged 7 commits into from
May 28, 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
18 changes: 9 additions & 9 deletions packages/block-library/src/image/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,12 @@ function block_core_image_render_lightbox( $block_content, $block ) {
// Image.
$p->next_tag( 'img' );
$p->set_attribute( 'data-wp-init', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on--load', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on-window--resize', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on-async--load', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on-async-window--resize', 'callbacks.setButtonStyles' );
// Sets an event callback on the `img` because the `figure` element can also
// contain a caption, and we don't want to trigger the lightbox when the
// caption is clicked.
$p->set_attribute( 'data-wp-on--click', 'actions.showLightbox' );
$p->set_attribute( 'data-wp-on-async--click', 'actions.showLightbox' );

$body_content = $p->get_updated_html();

Expand All @@ -209,7 +209,7 @@ class="lightbox-trigger"
aria-haspopup="dialog"
aria-label="' . esc_attr( $aria_label ) . '"
data-wp-init="callbacks.initTriggerButton"
data-wp-on--click="actions.showLightbox"
data-wp-on-async--click="actions.showLightbox"
data-wp-style--right="context.imageButtonRight"
data-wp-style--top="context.imageButtonTop"
>
Expand Down Expand Up @@ -258,12 +258,12 @@ class="wp-lightbox-overlay zoom"
data-wp-class--show-closing-animation="state.showClosingAnimation"
data-wp-watch="callbacks.setOverlayFocus"
data-wp-on--keydown="actions.handleKeydown"
data-wp-on--touchstart="actions.handleTouchStart"
data-wp-on-async--touchstart="actions.handleTouchStart"
data-wp-on--touchmove="actions.handleTouchMove"
data-wp-on--touchend="actions.handleTouchEnd"
data-wp-on--click="actions.hideLightbox"
data-wp-on-window--resize="callbacks.setOverlayStyles"
data-wp-on-window--scroll="actions.handleScroll"
data-wp-on-async--touchend="actions.handleTouchEnd"
data-wp-on-async--click="actions.hideLightbox"
data-wp-on-async-window--resize="callbacks.setOverlayStyles"
data-wp-on-async-window--scroll="actions.handleScroll"
tabindex="-1"
>
<button type="button" aria-label="$close_button_label" style="fill: $close_button_color" class="close-button">
Expand Down
8 changes: 6 additions & 2 deletions packages/interactivity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@

## Unreleased

### Bug fixes
### New Features

- Fix null and number strings as namespaces runtime error. ([#61960](https://github.com/WordPress/gutenberg/pull/61960/))
- Introduce `wp-on-async` directive as performant alternative over synchronous `wp-on` directive. ([#61885](https://github.com/WordPress/gutenberg/pull/61885))

### Breaking Changes

- Variables like `process.env.IS_GUTENBERG_PLUGIN` have been replaced by `globalThis.IS_GUTENBERG_PLUGIN`. Build systems using `process.env` should be updated ([#61486](https://github.com/WordPress/gutenberg/pull/61486)).
- Increase the minimum required Node.js version to v18.12.0 matching long-term support releases ([#31270](https://github.com/WordPress/gutenberg/pull/61930)). Learn more about [Node.js releases](https://nodejs.org/en/about/previous-releases).

### Bug fixes

- Fix null and number strings as namespaces runtime error. ([#61960](https://github.com/WordPress/gutenberg/pull/61960/))

## 5.7.0 (2024-05-16)

### Enhancements
Expand Down
92 changes: 84 additions & 8 deletions packages/interactivity/src/directives.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,17 @@ import { deepSignal, peek, type DeepSignal } from 'deepsignal';
/**
* Internal dependencies
*/
import { useWatch, useInit, kebabToCamelCase, warn } from './utils';
import {
useWatch,
useInit,
kebabToCamelCase,
warn,
yieldToMain,
} from './utils';
import type { DirectiveEntry } from './hooks';
import { directive, getScope, getEvaluate } from './hooks';

// Assigned objects should be ignore during proxification.
// Assigned objects should be ignored during proxification.
const contextAssignedObjects = new WeakMap();

// Store the context proxy and fallback for each object in the context.
Expand Down Expand Up @@ -213,10 +220,10 @@ const getGlobalEventDirective = ( type: 'window' | 'document' ) => {
return ( { directives, evaluate } ) => {
directives[ `on-${ type }` ]
.filter( ( { suffix } ) => suffix !== 'default' )
.forEach( ( entry ) => {
.forEach( ( entry: DirectiveEntry ) => {
const eventName = entry.suffix.split( '--', 1 )[ 0 ];
useInit( () => {
const cb = ( event ) => evaluate( entry, event );
const cb = ( event: Event ) => evaluate( entry, event );
const globalVar = type === 'window' ? window : document;
globalVar.addEventListener( eventName, cb );
return () => globalVar.removeEventListener( eventName, cb );
Expand All @@ -225,6 +232,33 @@ const getGlobalEventDirective = ( type: 'window' | 'document' ) => {
};
};

/**
* Creates a directive that adds an async event listener to the global window or
* document object.
*
* @param type 'window' or 'document'
*/
const getGlobalAsyncEventDirective = ( type: 'window' | 'document' ) => {
return ( { directives, evaluate } ) => {
directives[ `on-async-${ type }` ]
.filter( ( { suffix } ) => suffix !== 'default' )
.forEach( ( entry: DirectiveEntry ) => {
const eventName = entry.suffix.split( '--', 1 )[ 0 ];
useInit( () => {
const cb = async ( event: Event ) => {
await yieldToMain();
evaluate( entry, event );
};
const globalVar = type === 'window' ? window : document;
globalVar.addEventListener( eventName, cb, {
passive: true,
} );
return () => globalVar.removeEventListener( eventName, cb );
} );
} );
};
};

export default () => {
// data-wp-context
directive(
Expand Down Expand Up @@ -281,31 +315,73 @@ export default () => {

// data-wp-on--[event]
directive( 'on', ( { directives: { on }, element, evaluate } ) => {
const events = new Map();
const events = new Map< string, Set< DirectiveEntry > >();
on.filter( ( { suffix } ) => suffix !== 'default' ).forEach(
( entry ) => {
const event = entry.suffix.split( '--' )[ 0 ];
if ( ! events.has( event ) ) {
events.set( event, new Set() );
events.set( event, new Set< DirectiveEntry >() );
}
events.get( event ).add( entry );
events.get( event )!.add( entry );
}
);

events.forEach( ( entries, eventType ) => {
element.props[ `on${ eventType }` ] = ( event ) => {
const existingHandler = element.props[ `on${ eventType }` ];
element.props[ `on${ eventType }` ] = ( event: Event ) => {
entries.forEach( ( entry ) => {
if ( existingHandler ) {
existingHandler( event );
}
evaluate( entry, event );
} );
};
} );
} );

// data-wp-on-async--[event]
directive(
'on-async',
( { directives: { 'on-async': onAsync }, element, evaluate } ) => {
const events = new Map< string, Set< DirectiveEntry > >();
onAsync
.filter( ( { suffix } ) => suffix !== 'default' )
.forEach( ( entry ) => {
const event = entry.suffix.split( '--' )[ 0 ];
if ( ! events.has( event ) ) {
events.set( event, new Set< DirectiveEntry >() );
}
events.get( event )!.add( entry );
} );

events.forEach( ( entries, eventType ) => {
const existingHandler = element.props[ `on${ eventType }` ];
element.props[ `on${ eventType }` ] = ( event: Event ) => {
if ( existingHandler ) {
existingHandler( event );
}
entries.forEach( async ( entry ) => {
await yieldToMain();
evaluate( entry, event );
} );
};
} );
}
);

// data-wp-on-window--[event]
directive( 'on-window', getGlobalEventDirective( 'window' ) );
// data-wp-on-document--[event]
directive( 'on-document', getGlobalEventDirective( 'document' ) );

// data-wp-on-async-window--[event]
directive( 'on-async-window', getGlobalAsyncEventDirective( 'window' ) );
// data-wp-on-async-document--[event]
directive(
'on-async-document',
getGlobalAsyncEventDirective( 'document' )
);

// data-wp-class--[classname]
directive(
'class',
Expand Down
2 changes: 1 addition & 1 deletion packages/interactivity/src/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import type { VNode, Context, RefObject } from 'preact';
*/
import { store, stores, universalUnlock } from './store';
import { warn } from './utils';
interface DirectiveEntry {
export interface DirectiveEntry {
value: string | object;
namespace: string;
suffix: string;
Expand Down
9 changes: 1 addition & 8 deletions packages/interactivity/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { hydrate, type ContainerNode, type ComponentChild } from 'preact';
* Internal dependencies
*/
import { toVdom, hydratedIslands } from './vdom';
import { createRootFragment } from './utils';
import { createRootFragment, yieldToMain } from './utils';
import { directivePrefix } from './constants';

// Keep the same root fragment for each interactive region node.
Expand All @@ -24,13 +24,6 @@ export const getRegionRootFragment = ( region: Element ): ContainerNode => {
return regionRootFragments.get( region );
};

function yieldToMain() {
return new Promise( ( resolve ) => {
// TODO: Use scheduler.yield() when available.
setTimeout( resolve, 0 );
} );
}

// Initial vDOM regions associated with its DOM element.
export const initialVdom = new WeakMap< Element, ComponentChild[] >();

Expand Down
12 changes: 12 additions & 0 deletions packages/interactivity/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ const afterNextFrame = ( callback: () => void ) => {
} );
};

/**
* Returns a promise that resolves after yielding to main.
*
* @return Promise
*/
export const yieldToMain = () => {
return new Promise( ( resolve ) => {
// TODO: Use scheduler.yield() when available.
setTimeout( resolve, 0 );
} );
};

/**
* Creates a Flusher object that can be used to flush computed values and notify listeners.
*
Expand Down
Loading