Skip to content

Commit

Permalink
Prevent saving content model without a name (#123)
Browse files Browse the repository at this point in the history
  • Loading branch information
zaguiini authored Sep 5, 2024
1 parent 11846ab commit d9755f9
Showing 1 changed file with 15 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,27 @@ import { store as editorStore } from '@wordpress/editor';
import { store as noticesStore } from '@wordpress/notices';

export const useContentModelNameLengthRestrictor = () => {
const { editPost } = useDispatch( editorStore );
const { editPost, lockPostSaving, unlockPostSaving } =
useDispatch( editorStore );
const { createNotice } = useDispatch( noticesStore );

const title = useSelect( ( select ) =>
select( editorStore ).getEditedPostAttribute( 'title' )
);

useEffect( () => {
if ( title && title.length > 20 ) {
editPost( { title: title.substring( 0, 20 ) } );
const trimmedTitle = title?.trim() ?? '';

if ( trimmedTitle.length === 0 ) {
lockPostSaving( 'title-empty-lock' );
return;
}

unlockPostSaving( 'title-empty-lock' );

editPost( { title: trimmedTitle.substring( 0, 20 ) } );

if ( trimmedTitle.length > 20 ) {
createNotice(
'warning',
__( 'Title is limited to 20 characters.' ),
Expand All @@ -24,5 +35,5 @@ export const useContentModelNameLengthRestrictor = () => {
}
);
}
}, [ title, editPost, createNotice ] );
}, [ title, lockPostSaving, unlockPostSaving, editPost, createNotice ] );
};

0 comments on commit d9755f9

Please sign in to comment.