File size: 2,164 Bytes
1e92f2d |
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 |
import { deserialize as _recurse } from '../';
/**
* Module variables
*/
const REGEXP_CAPTION_CONTENT = /((?:<a [^>]+>)?<img [^>]+>(?:<\/a>)?)([\s\S]*)/i;
const REGEXP_CAPTION_ID = /attachment_(\d+)/;
const REGEXP_CAPTION_ALIGN = /align(\w+)/;
/**
* Given a caption shortcode object, returns an object of parsed attributes.
* @param {Object} node Caption shortcode object
* @param {Object} _parsed In recursion, the known values
* @returns {Object} Object of all detected values
*/
function parseCaption( node, _parsed ) {
// Pull named attributes
if ( node.attrs && node.attrs.named ) {
// Caption align is suffixed with "align"
if ( REGEXP_CAPTION_ALIGN.test( node.attrs.named.align ) ) {
_parsed.appearance.align = node.attrs.named.align.match( REGEXP_CAPTION_ALIGN )[ 1 ];
}
// Caption ID is suffixed with "attachment_"
if ( REGEXP_CAPTION_ID.test( node.attrs.named.id ) ) {
_parsed.media.ID = parseInt( node.attrs.named.id.match( REGEXP_CAPTION_ID )[ 1 ], 10 );
}
// Extract dimensions
if ( _parsed.media.width && isFinite( node.attrs.named.width ) ) {
_parsed.media.width = parseInt( node.attrs.named.width, 10 );
}
}
// If shortcode contains no content, we're finished at this point
if ( ! node.content ) {
return _parsed;
}
// Extract shortcode content, including caption text as sibling
// adjacent to the image itself.
const img = node.content.match( REGEXP_CAPTION_CONTENT );
if ( img && img[ 2 ] ) {
_parsed.media.caption = img[ 2 ].trim();
}
// If content contains image in addition to caption text, continue
// to parse the image
if ( img ) {
return _recurse( img[ 1 ], _parsed );
}
return _parsed;
}
/**
* Given a media shortcode object, returns an object containing all detected
* values.
* @param {Object} node Media shortcode object to parse
* @param {Object} _parsed In recursion, the known values
* @returns {Object} Object of all detected values
*/
export function deserialize( node, _parsed = { media: {}, appearance: {} } ) {
switch ( node.tag ) {
case 'caption':
_parsed = parseCaption( node, _parsed );
break;
}
return _parsed;
}
|