-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathedit.js
101 lines (89 loc) · 2.64 KB
/
edit.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* External dependencies
*/
import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { _x, _n, sprintf } from '@wordpress/i18n';
import { useMemo } from '@wordpress/element';
import {
AlignmentControl,
BlockControls,
useBlockProps,
} from '@wordpress/block-editor';
import { __unstableSerializeAndClean } from '@wordpress/blocks';
import { useEntityProp, useEntityBlockEditor } from '@wordpress/core-data';
import { count as wordCount } from '@wordpress/wordcount';
/**
* Average reading rate - based on average taken from
* https://irisreading.com/average-reading-speed-in-various-languages/
* (Characters/minute used for Chinese rather than words).
*/
const AVERAGE_READING_RATE = 189;
function PostTimeToReadEdit( { attributes, setAttributes, context } ) {
const { textAlign } = attributes;
const { postId, postType } = context;
const [ contentStructure ] = useEntityProp(
'postType',
postType,
'content',
postId
);
const [ blocks ] = useEntityBlockEditor( 'postType', postType, {
id: postId,
} );
const minutesToReadString = useMemo( () => {
// Replicates the logic found in getEditedPostContent().
let content;
if ( contentStructure instanceof Function ) {
content = contentStructure( { blocks } );
} else if ( blocks ) {
// If we have parsed blocks already, they should be our source of truth.
// Parsing applies block deprecations and legacy block conversions that
// unparsed content will not have.
content = __unstableSerializeAndClean( blocks );
} else {
content = contentStructure;
}
/*
* 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 minutesToRead = Math.max(
1,
Math.round(
wordCount( content, wordCountType ) / AVERAGE_READING_RATE
)
);
return sprintf(
/* translators: %d is the number of minutes the post will take to read. */
_n( '%d minute', '%d minutes', minutesToRead ),
minutesToRead
);
}, [ contentStructure, blocks ] );
const blockProps = useBlockProps( {
className: classnames( {
[ `has-text-align-${ textAlign }` ]: textAlign,
} ),
} );
return (
<>
<BlockControls group="block">
<AlignmentControl
value={ textAlign }
onChange={ ( nextAlign ) => {
setAttributes( { textAlign: nextAlign } );
} }
/>
</BlockControls>
<div { ...blockProps }>{ minutesToReadString }</div>
</>
);
}
export default PostTimeToReadEdit;