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

withNotices: Convert to TypeScript #49088

Merged
merged 4 commits into from
Mar 15, 2023
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
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
- `withFocusReturn` HOC: Convert to TypeScript ([#48748](https://github.com/WordPress/gutenberg/pull/48748)).
- `navigateRegions` HOC: Convert to TypeScript ([#48632](https://github.com/WordPress/gutenberg/pull/48632)).
- `withSpokenMessages`: HOC: Convert to TypeScript ([#48163](https://github.com/WordPress/gutenberg/pull/48163)).
- `withNotices`: HOC: Convert to TypeScript ([#49088](https://github.com/WordPress/gutenberg/pull/49088)).
- `ToolbarButton`: Convert to TypeScript ([#47750](https://github.com/WordPress/gutenberg/pull/47750)).
- `DimensionControl(Experimental)`: Convert to TypeScript ([#47351](https://github.com/WordPress/gutenberg/pull/47351)).
- `PaletteEdit`: Convert to TypeScript ([#47764](https://github.com/WordPress/gutenberg/pull/47764)).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

`withNotices` is a React [higher-order component](https://facebook.github.io/react/docs/higher-order-components.html) used typically in adding the ability to post notice messages within the original component.

Wrapping the original component with `withNotices` encapsulates the component with the additional props `noticeOperations` and `noticeUI`.
Wrapping the original component with `withNotices` encapsulates the component with the additional props `noticeOperations`, `noticeUI`, and `noticeList`.

**noticeOperations**
Contains a number of useful functions to add notices to your site.
Expand Down Expand Up @@ -34,6 +34,9 @@ _Parameters_
<a name="noticeUi" href="#noticeUi">#</a>**noticeUi**
The rendered `NoticeList`.

<a name="noticeList" href="#noticeList">#</a>**noticeList**
The array of notice objects to be displayed.

## Usage

```jsx
Expand Down
104 changes: 0 additions & 104 deletions packages/components/src/higher-order/with-notices/index.js

This file was deleted.

116 changes: 116 additions & 0 deletions packages/components/src/higher-order/with-notices/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* External dependencies
*/
import { v4 as uuid } from 'uuid';

/**
* WordPress dependencies
*/
import { forwardRef, useState, useMemo } from '@wordpress/element';
import { createHigherOrderComponent } from '@wordpress/compose';

/**
* Internal dependencies
*/
import NoticeList from '../../notice/list';
import type { WithNoticeProps } from './types';

/**
* Override the default edit UI to include notices if supported.
*
* Wrapping the original component with `withNotices` encapsulates the component
* with the additional props `noticeOperations` and `noticeUI`.
*
* ```jsx
* import { withNotices, Button } from '@wordpress/components';
*
* const MyComponentWithNotices = withNotices(
* ( { noticeOperations, noticeUI } ) => {
* const addError = () =>
* noticeOperations.createErrorNotice( 'Error message' );
* return (
* <div>
* { noticeUI }
* <Button variant="secondary" onClick={ addError }>
* Add error
* </Button>
* </div>
* );
* }
* );
* ```
*
* @param OriginalComponent Original component.
*
* @return Wrapped component.
*/
export default createHigherOrderComponent( ( OriginalComponent ) => {
function Component(
props: { [ key: string ]: any },
Copy link
Contributor

Choose a reason for hiding this comment

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

Not necessarily for this PR, but we should find a way for consumers of this HOC to get type checks on these props (ie. if they are compatible with OriginalComponent's prop types)

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, I believe this will require TS changes in the createHigherOrderComponent function so the return function can take a generic argument.

ref: React.ForwardedRef< any >
) {
const [ noticeList, setNoticeList ] = useState<
WithNoticeProps[ 'noticeList' ]
>( [] );

const noticeOperations = useMemo<
WithNoticeProps[ 'noticeOperations' ]
>( () => {
const createNotice: WithNoticeProps[ 'noticeOperations' ][ 'createNotice' ] =
( notice ) => {
const noticeToAdd = notice.id
? notice
: { ...notice, id: uuid() };
setNoticeList( ( current ) => [ ...current, noticeToAdd ] );
};

return {
createNotice,
createErrorNotice: ( msg ) => {
// @ts-expect-error TODO: Missing `id`, potentially a bug
createNotice( {
status: 'error',
content: msg,
} );
},
removeNotice: ( id ) => {
setNoticeList( ( current ) =>
current.filter( ( notice ) => notice.id !== id )
);
},
removeAllNotices: () => {
setNoticeList( [] );
},
};
}, [] );

const propsOut = {
...props,
noticeList,
noticeOperations,
noticeUI: noticeList.length > 0 && (
<NoticeList
className="components-with-notices-ui"
notices={ noticeList }
onRemove={ noticeOperations.removeNotice }
/>
),
};

return isForwardRef ? (
<OriginalComponent { ...propsOut } ref={ ref } />
) : (
<OriginalComponent { ...propsOut } />
);
}

let isForwardRef: boolean;
// @ts-expect-error - `render` will only be present when OriginalComponent was wrapped with forwardRef().
const { render } = OriginalComponent;
// Returns a forwardRef if OriginalComponent appears to be a forwardRef.
if ( typeof render === 'function' ) {
isForwardRef = true;
return forwardRef( Component );
}
return Component;
}, 'withNotices' );
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,30 @@ import {
* Internal dependencies
*/
import withNotices from '..';
import type { WithNoticeProps } from '../types';

// Implementation detail of Notice component used to query the dismissal button.
const stockDismissText = 'Dismiss this notice';

function noticesFrom( list ) {
function noticesFrom( list: string[] ) {
return list.map( ( item ) => ( { id: item, content: item } ) );
}

function isComponentLike( object ) {
function isComponentLike( object: any ) {
return typeof object === 'function';
}

function isForwardRefLike( { render: renderMethod } ) {
function isForwardRefLike( { render: renderMethod }: any ) {
return typeof renderMethod === 'function';
}

const content = 'Base content';

const BaseComponent = ( { noticeOperations, noticeUI, notifications } ) => {
const BaseComponent = ( {
noticeOperations,
noticeUI,
notifications,
}: WithNoticeProps & { notifications: ReturnType< typeof noticesFrom > } ) => {
useEffect( () => {
if ( notifications ) {
notifications.forEach( ( item ) =>
Expand Down Expand Up @@ -78,8 +83,8 @@ describe( 'withNotices return type', () => {
} );

describe( 'withNotices operations', () => {
let handle;
const Handle = ( props ) => {
let handle: React.MutableRefObject< any >;
const Handle = ( props: any ) => {
handle = useRef();
return <TestNoticeOperations { ...props } ref={ handle } />;
};
Expand Down
35 changes: 35 additions & 0 deletions packages/components/src/higher-order/with-notices/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Internal dependencies
*/
import type { NoticeListProps } from '../../notice/types';

export type WithNoticeProps = {
noticeList: NoticeListProps[ 'notices' ];
mirka marked this conversation as resolved.
Show resolved Hide resolved
noticeOperations: {
/**
* Function passed down as a prop that adds a new notice.
*
* @param notice Notice to add.
*/
createNotice: (
notice: NoticeListProps[ 'notices' ][ number ]
) => void;
/**
* Function passed as a prop that adds a new error notice.
*
* @param msg Error message of the notice.
*/
createErrorNotice: ( msg: string ) => void;
/**
* Removes a notice by id.
*
* @param id Id of the notice to remove.
*/
removeNotice: ( id: string ) => void;
/**
* Removes all notices
*/
removeAllNotices: () => void;
};
noticeUI: false | JSX.Element;
};
3 changes: 1 addition & 2 deletions packages/components/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
"src/**/stories/**/*.js", // only exclude js files, tsx files should be checked
"src/**/test/**/*.js", // only exclude js files, ts{x} files should be checked
"src/index.js",
"src/duotone-picker",
"src/higher-order/with-notices"
"src/duotone-picker"
]
}