Skip to content

Commit

Permalink
Interactivity API: Refactor context proxies (#64713)
Browse files Browse the repository at this point in the history
* Move `proxifyContext` to proxies folder

* Move context handlers outside

* Remove unused code

* Update comment

* Add TODO comment

* Remove unused code and rename `k` arg to `key`

* Replace `updateContext` with `deepMerge`

* Throw when calling `proxifyContext` on a context proxy

* Add unit tests

* Update changelog

* Added new tests
to validate behavior with proxified state. Also included more descriptive error messages for re-proxification attempts.

---------

Co-authored-by: DAreRodz <darerodz@git.wordpress.org>
Co-authored-by: michalczaplinski <czapla@git.wordpress.org>
Co-authored-by: luisherranz <luisherranz@git.wordpress.org>
  • Loading branch information
4 people authored Sep 17, 2024
1 parent 93af2dd commit 636710b
Show file tree
Hide file tree
Showing 5 changed files with 369 additions and 131 deletions.
4 changes: 4 additions & 0 deletions packages/interactivity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Unreleased

### Enhancements

- Refactor internal context proxies implementation ([#64713](https://github.com/WordPress/gutenberg/pull/64713)).

### Bug Fixes

- Prevent calling `proxifyContext` over an already-proxified context inside `wp-context` ([#65090](https://github.com/WordPress/gutenberg/pull/65090)).
Expand Down
135 changes: 4 additions & 131 deletions packages/interactivity/src/directives.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@
*/
import { h as createElement, type RefObject } from 'preact';
import { useContext, useMemo, useRef } from 'preact/hooks';
/**
* Internal dependencies
*/
import { proxifyState, peek } from './proxies';

/**
* Internal dependencies
Expand All @@ -24,131 +20,7 @@ import {
} from './utils';
import { directive, getEvaluate, type DirectiveEntry } from './hooks';
import { getScope } from './scopes';

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

// Store the context proxy and fallback for each object in the context.
const contextObjectToProxy = new WeakMap();
const contextProxyToObject = new WeakMap();
const contextObjectToFallback = new WeakMap();

const descriptor = Reflect.getOwnPropertyDescriptor;

/**
* Wrap a context object with a proxy to reproduce the context stack. The proxy
* uses the passed `inherited` context as a fallback to look up for properties
* that don't exist in the given context. Also, updated properties are modified
* where they are defined, or added to the main context when they don't exist.
*
* By default, all plain objects inside the context are wrapped, unless it is
* listed in the `ignore` option.
*
* @param current Current context.
* @param inherited Inherited context, used as fallback.
*
* @return The wrapped context object.
*/
const proxifyContext = ( current: object, inherited: object = {} ): object => {
// Update the fallback object reference when it changes.
contextObjectToFallback.set( current, inherited );
if ( ! contextObjectToProxy.has( current ) ) {
const proxy = new Proxy( current, {
get: ( target: object, k: string ) => {
const fallback = contextObjectToFallback.get( current );
// Always subscribe to prop changes in the current context.
const currentProp = target[ k ];

// Return the inherited prop when missing in target.
if ( ! ( k in target ) && k in fallback ) {
return fallback[ k ];
}

// Proxify plain objects that were not directly assigned.
if (
k in target &&
! contextAssignedObjects.get( target )?.has( k ) &&
isPlainObject( currentProp )
) {
return proxifyContext( currentProp );
}

// Return the stored proxy for `currentProp` when it exists.
if ( contextObjectToProxy.has( currentProp ) ) {
return contextObjectToProxy.get( currentProp );
}

/*
* For other cases, return the value from target, also
* subscribing to changes in the parent context when the current
* prop is not defined.
*/
return k in target ? currentProp : fallback[ k ];
},
set: ( target, k, value ) => {
const fallback = contextObjectToFallback.get( current );
const obj =
k in target || ! ( k in fallback ) ? target : fallback;

/*
* Assigned object values should not be proxified so they point
* to the original object and don't inherit unexpected
* properties.
*/
if ( value && typeof value === 'object' ) {
if ( ! contextAssignedObjects.has( obj ) ) {
contextAssignedObjects.set( obj, new Set() );
}
contextAssignedObjects.get( obj ).add( k );
}

/*
* When the value is a proxy, it's because it comes from the
* context, so the inner value is assigned instead.
*/
if ( contextProxyToObject.has( value ) ) {
const innerValue = contextProxyToObject.get( value );
obj[ k ] = innerValue;
} else {
obj[ k ] = value;
}

return true;
},
ownKeys: ( target ) => [
...new Set( [
...Object.keys( contextObjectToFallback.get( current ) ),
...Object.keys( target ),
] ),
],
getOwnPropertyDescriptor: ( target, k ) =>
descriptor( target, k ) ||
descriptor( contextObjectToFallback.get( current ), k ),
} );
contextObjectToProxy.set( current, proxy );
contextProxyToObject.set( proxy, current );
}
return contextObjectToProxy.get( current );
};

/**
* Recursively update values within a context object.
*
* @param target A context instance.
* @param source Object with properties to update in `target`.
*/
const updateContext = ( target: any, source: any ) => {
for ( const k in source ) {
if (
isPlainObject( peek( target, k ) ) &&
isPlainObject( source[ k ] )
) {
updateContext( peek( target, k ) as object, source[ k ] );
} else if ( ! ( k in target ) ) {
target[ k ] = source[ k ];
}
}
};
import { proxifyState, proxifyContext, deepMerge } from './proxies';

/**
* Recursively clone the passed object.
Expand Down Expand Up @@ -286,9 +158,10 @@ export default () => {
`The value of data-wp-context in "${ namespace }" store must be a valid stringified JSON object.`
);
}
updateContext(
deepMerge(
currentValue.current,
deepClone( value ) as object
deepClone( value ) as object,
false
);
result[ namespace ] = proxifyContext(
currentValue.current,
Expand Down
69 changes: 69 additions & 0 deletions packages/interactivity/src/proxies/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
const contextObjectToProxy = new WeakMap();
const contextObjectToFallback = new WeakMap();
const contextProxies = new WeakSet();

const descriptor = Reflect.getOwnPropertyDescriptor;

// TODO: Use the proxy registry to avoid multiple proxies on the same object.
const contextHandlers: ProxyHandler< object > = {
get: ( target, key ) => {
const fallback = contextObjectToFallback.get( target );
// Always subscribe to prop changes in the current context.
const currentProp = target[ key ];

/*
* Return the value from `target` if it exists, or from `fallback`
* otherwise. This way, in the case the property doesn't exist either in
* `target` or `fallback`, it also subscribes to changes in the parent
* context.
*/
return key in target ? currentProp : fallback[ key ];
},
set: ( target, key, value ) => {
const fallback = contextObjectToFallback.get( target );

// If the property exists in the current context, modify it. Otherwise,
// add it to the current context.
const obj = key in target || ! ( key in fallback ) ? target : fallback;
obj[ key ] = value;

return true;
},
ownKeys: ( target ) => [
...new Set( [
...Object.keys( contextObjectToFallback.get( target ) ),
...Object.keys( target ),
] ),
],
getOwnPropertyDescriptor: ( target, key ) =>
descriptor( target, key ) ||
descriptor( contextObjectToFallback.get( target ), key ),
};

/**
* Wrap a context object with a proxy to reproduce the context stack. The proxy
* uses the passed `inherited` context as a fallback to look up for properties
* that don't exist in the given context. Also, updated properties are modified
* where they are defined, or added to the main context when they don't exist.
*
* @param current Current context.
* @param inherited Inherited context, used as fallback.
*
* @return The wrapped context object.
*/
export const proxifyContext = (
current: object,
inherited: object = {}
): object => {
if ( contextProxies.has( current ) ) {
throw Error( 'This object cannot be proxified.' );
}
// Update the fallback object reference when it changes.
contextObjectToFallback.set( current, inherited );
if ( ! contextObjectToProxy.has( current ) ) {
const proxy = new Proxy( current, contextHandlers );
contextObjectToProxy.set( current, proxy );
contextProxies.add( proxy );
}
return contextObjectToProxy.get( current );
};
1 change: 1 addition & 0 deletions packages/interactivity/src/proxies/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
*/
export { proxifyState, peek, deepMerge } from './state';
export { proxifyStore } from './store';
export { proxifyContext } from './context';
Loading

1 comment on commit 636710b

@github-actions
Copy link

Choose a reason for hiding this comment

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

Flaky tests detected in 636710b.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/10908245521
📝 Reported issues:

Please sign in to comment.