Skip to content

Commit

Permalink
Support word count types
Browse files Browse the repository at this point in the history
  • Loading branch information
carolinan committed Nov 22, 2022
1 parent 1d686af commit 86342e2
Showing 1 changed file with 44 additions and 10 deletions.
54 changes: 44 additions & 10 deletions packages/block-library/src/post-excerpt/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,35 +101,69 @@ export default function PostExcerptEditor( {
'is-inline': ! showMoreOnNewLine,
} );

/*
/**
* translators: If your word count is based on single characters (e.g. East Asian characters),
* enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
* Do not translate into your own language.
*/
const wordCountType = _x( 'words', 'Word count type. Do not translate!' );

const currentWordCount = wordCount( rawExcerpt, wordCountType );

/**
* The excerpt length setting needs to be applied to both
* the raw and the rendered excerpt depending on which is being used.
*/
const rawOrRenderedExcerpt = !! renderedExcerpt
? strippedRenderedExcerpt
: rawExcerpt;

let trimmedExcerpt = '';
if ( wordCountType === 'words' ) {
trimmedExcerpt = rawOrRenderedExcerpt
.trim()
.split( ' ', excerptLength )
.join( ' ' );
} else if ( wordCountType === 'characters_excluding_spaces' ) {
/*
* 1. Split the excerpt at the character limit,
* then join the substrings back into one string.
* 2. Count the number of spaces in the excerpt
* by comparing the lengths of the string with and without spaces.
* 3. Add the number to the length of the visible excerpt,
* so that the spaces are excluded from the word count.
*/
const excerptWithSpaces = rawOrRenderedExcerpt
.trim()
.split( '', excerptLength )
.join( '' );

const numberOfSpaces =
excerptWithSpaces.length -
excerptWithSpaces.replaceAll( ' ', '' ).length;

trimmedExcerpt = rawOrRenderedExcerpt
.trim()
.split( '', excerptLength + numberOfSpaces )
.join( '' );
} else if ( wordCountType === 'characters_including_spaces' ) {
trimmedExcerpt = rawOrRenderedExcerpt.trim().split( '', excerptLength );
}

const excerptContent = isEditable ? (
<RichText
className={ excerptClassName }
aria-label={ __( 'Post excerpt text' ) }
value={
rawExcerpt.trim().split( ' ', excerptLength ).join( ' ' ) ||
strippedRenderedExcerpt
.trim()
.split( ' ', excerptLength )
.join( ' ' ) ||
trimmedExcerpt ||
( isSelected ? '' : __( 'No post excerpt found' ) )
}
onChange={ setExcerpt }
tagName="p"
/>
) : (
<p className={ excerptClassName }>
{ strippedRenderedExcerpt
.trim()
.split( ' ', excerptLength )
.join( ' ' ) || __( 'No post excerpt found' ) }
{ trimmedExcerpt || __( 'No post excerpt found' ) }
</p>
);
return (
Expand Down

0 comments on commit 86342e2

Please sign in to comment.