PluginProbe
BeyondWords – AI audio for publishers / 4.2.4
BeyondWords – AI audio for publishers v4.2.4
7.1.0 trunk 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.0.5 4.0.6 4.1.0 4.1.1 4.1.2 4.2.0 4.2.1 4.2.2 4.2.3 4.2.4 4.3.0 4.4.0 4.5.0 4.5.1 4.6.0 4.6.1 4.6.2 4.7.0 All 43 releases
speechkit / src / Component / Post / BlockAttributes / helpers / getBlockMarkerAttribute.js

getBlockMarkerAttribute.js in BeyondWords – AI audio for publishers 4.2.4, at src/Component/Post/BlockAttributes/helpers/getBlockMarkerAttribute.js

80 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /**
2 * WordPress Dependencies
3 */
4 import { select } from '@wordpress/data';
5
6 /**
7 * External dependencies
8 */
9 import { v4 as uuidv4 } from 'uuid';
10
11 /**
12 * Get a beyondwordsMarker attribute for a block.
13 *
14 * Using the "Duplicate" button in the Block toolbar duplicates the marker
15 * attribute too, so we attempt to handle this by getting all the markers in the
16 * current Post and assinging new UUIDs to markers that already exist.
17 *
18 * @since 4.0.0
19 *
20 * @param {Object} attributes Attributes for the block.
21 *
22 * @return {String} marker The block marker (segment marker in BeyondWords API).
23 */
24 const getBlockMarkerAttribute = ( attributes ) => {
25 const { beyondwordsMarker } = attributes;
26
27 if ( ! beyondwordsMarker ) return uuidv4();
28
29 const existingMarkers = getExistingBlockMarkers()
30
31 if ( countInArray( existingMarkers, beyondwordsMarker ) > 1 ) {
32 // Return a new UUID if this marker is a duplicate
33 return uuidv4();
34 }
35
36 // Return the existing marker only if it is not a duplicate
37 return beyondwordsMarker;
38 }
39
40 /**
41 * Get all existing Block markers for the currently-edited post.
42 *
43 * If using `getBlocks()` proves to be too respource-intensive then further work
44 * will be required to optimise this.
45 *
46 * @since 4.0.0
47 *
48 * @return {String[]} markers The block markers for the current Post.
49 */
50 const getExistingBlockMarkers = () => {
51 // Get all Blocks in current Post
52 const blocks = select( 'core/block-editor' )
53 .getBlocks();
54
55 // Return all non-empty markers of the Blocks
56 return blocks
57 .map( block => block?.attributes?.beyondwordsMarker )
58 .filter( marker => marker );
59 }
60
61 /**
62 * Count the number of times an item is in an array.
63 *
64 * @since 4.0.0
65 *
66 * @return {Number} count The number of times the item occurs.
67 */
68 function countInArray(array, item) {
69 var count = 0;
70
71 for ( var i = 0; i < array.length; i++ ) {
72 if ( array[ i ] === item ) {
73 count++;
74 }
75 }
76
77 return count;
78 }
79
80 export default getBlockMarkerAttribute;