| 1 |
/** |
| 2 |
* Common functions for the TablePress/table block. |
| 3 |
* |
| 4 |
* @package TablePress |
| 5 |
* @subpackage Blocks |
| 6 |
* @author Tobias Bäthge |
| 7 |
* @since 2.0.0 |
| 8 |
*/ |
| 9 |
|
| 10 |
/** |
| 11 |
* Converts a set of named and numeric Shortcode attributes to a string. |
| 12 |
* |
| 13 |
* This function is similar to @wordpress/shortcode's `string()` function, |
| 14 |
* but only returns the attributes string and not a full Shortcode. |
| 15 |
* |
| 16 |
* @param {Object} shortcodeAttrs The named and numeric Shortcode attributes. |
| 17 |
* @return {string} The attributes as a key=value string. |
| 18 |
*/ |
| 19 |
export const shortcode_attrs_to_string = ( shortcodeAttrs ) => { |
| 20 |
// Convert named attributes. |
| 21 |
let shortcode_attrs_string = Object.entries( shortcodeAttrs.named ).map( ( [ attribute, value ] ) => { |
| 22 |
let enclose = ''; // Don't enclose values by default. |
| 23 |
|
| 24 |
// Remove curly quotation marks around a value. |
| 25 |
value = value.replace( /“([^”]*)”/g, '$1' ); |
| 26 |
|
| 27 |
// Use " as delimiter if value contains whitespace or is empty. |
| 28 |
if ( /\s/.test( value ) || '' === value ) { |
| 29 |
enclose = '"'; |
| 30 |
} |
| 31 |
|
| 32 |
// Use ' as delimiter if value contains ". |
| 33 |
if ( value.includes( '"' ) ) { |
| 34 |
enclose = '\''; |
| 35 |
} |
| 36 |
|
| 37 |
return `${ attribute }=${ enclose }${ value }${ enclose }`; |
| 38 |
} ).join( ' ' ); |
| 39 |
|
| 40 |
// Convert numeric attributes. |
| 41 |
shortcodeAttrs.numeric.forEach( ( value ) => { |
| 42 |
if ( /\s/.test( value ) ) { |
| 43 |
shortcode_attrs_string += ' "' + value + '"'; |
| 44 |
} else { |
| 45 |
shortcode_attrs_string += ' ' + value; |
| 46 |
} |
| 47 |
} ); |
| 48 |
|
| 49 |
return shortcode_attrs_string; |
| 50 |
}; |
| 51 |
|