shortcode.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /**
  2. * Utility functions for parsing and handling shortcodes in JavaScript.
  3. *
  4. * @output wp-includes/js/shortcode.js
  5. */
  6. /**
  7. * Ensure the global `wp` object exists.
  8. *
  9. * @namespace wp
  10. */
  11. window.wp = window.wp || {};
  12. (function(){
  13. wp.shortcode = {
  14. // ### Find the next matching shortcode
  15. //
  16. // Given a shortcode `tag`, a block of `text`, and an optional starting
  17. // `index`, returns the next matching shortcode or `undefined`.
  18. //
  19. // Shortcodes are formatted as an object that contains the match
  20. // `content`, the matching `index`, and the parsed `shortcode` object.
  21. next: function( tag, text, index ) {
  22. var re = wp.shortcode.regexp( tag ),
  23. match, result;
  24. re.lastIndex = index || 0;
  25. match = re.exec( text );
  26. if ( ! match ) {
  27. return;
  28. }
  29. // If we matched an escaped shortcode, try again.
  30. if ( '[' === match[1] && ']' === match[7] ) {
  31. return wp.shortcode.next( tag, text, re.lastIndex );
  32. }
  33. result = {
  34. index: match.index,
  35. content: match[0],
  36. shortcode: wp.shortcode.fromMatch( match )
  37. };
  38. // If we matched a leading `[`, strip it from the match
  39. // and increment the index accordingly.
  40. if ( match[1] ) {
  41. result.content = result.content.slice( 1 );
  42. result.index++;
  43. }
  44. // If we matched a trailing `]`, strip it from the match.
  45. if ( match[7] ) {
  46. result.content = result.content.slice( 0, -1 );
  47. }
  48. return result;
  49. },
  50. // ### Replace matching shortcodes in a block of text
  51. //
  52. // Accepts a shortcode `tag`, content `text` to scan, and a `callback`
  53. // to process the shortcode matches and return a replacement string.
  54. // Returns the `text` with all shortcodes replaced.
  55. //
  56. // Shortcode matches are objects that contain the shortcode `tag`,
  57. // a shortcode `attrs` object, the `content` between shortcode tags,
  58. // and a boolean flag to indicate if the match was a `single` tag.
  59. replace: function( tag, text, callback ) {
  60. return text.replace( wp.shortcode.regexp( tag ), function( match, left, tag, attrs, slash, content, closing, right ) {
  61. // If both extra brackets exist, the shortcode has been
  62. // properly escaped.
  63. if ( left === '[' && right === ']' ) {
  64. return match;
  65. }
  66. // Create the match object and pass it through the callback.
  67. var result = callback( wp.shortcode.fromMatch( arguments ) );
  68. // Make sure to return any of the extra brackets if they
  69. // weren't used to escape the shortcode.
  70. return result ? left + result + right : match;
  71. });
  72. },
  73. // ### Generate a string from shortcode parameters
  74. //
  75. // Creates a `wp.shortcode` instance and returns a string.
  76. //
  77. // Accepts the same `options` as the `wp.shortcode()` constructor,
  78. // containing a `tag` string, a string or object of `attrs`, a boolean
  79. // indicating whether to format the shortcode using a `single` tag, and a
  80. // `content` string.
  81. string: function( options ) {
  82. return new wp.shortcode( options ).string();
  83. },
  84. // ### Generate a RegExp to identify a shortcode
  85. //
  86. // The base regex is functionally equivalent to the one found in
  87. // `get_shortcode_regex()` in `wp-includes/shortcodes.php`.
  88. //
  89. // Capture groups:
  90. //
  91. // 1. An extra `[` to allow for escaping shortcodes with double `[[]]`
  92. // 2. The shortcode name
  93. // 3. The shortcode argument list
  94. // 4. The self closing `/`
  95. // 5. The content of a shortcode when it wraps some content.
  96. // 6. The closing tag.
  97. // 7. An extra `]` to allow for escaping shortcodes with double `[[]]`
  98. regexp: _.memoize( function( tag ) {
  99. return new RegExp( '\\[(\\[?)(' + tag + ')(?![\\w-])([^\\]\\/]*(?:\\/(?!\\])[^\\]\\/]*)*?)(?:(\\/)\\]|\\](?:([^\\[]*(?:\\[(?!\\/\\2\\])[^\\[]*)*)(\\[\\/\\2\\]))?)(\\]?)', 'g' );
  100. }),
  101. // ### Parse shortcode attributes
  102. //
  103. // Shortcodes accept many types of attributes. These can chiefly be
  104. // divided into named and numeric attributes:
  105. //
  106. // Named attributes are assigned on a key/value basis, while numeric
  107. // attributes are treated as an array.
  108. //
  109. // Named attributes can be formatted as either `name="value"`,
  110. // `name='value'`, or `name=value`. Numeric attributes can be formatted
  111. // as `"value"` or just `value`.
  112. attrs: _.memoize( function( text ) {
  113. var named = {},
  114. numeric = [],
  115. pattern, match;
  116. // This regular expression is reused from `shortcode_parse_atts()`
  117. // in `wp-includes/shortcodes.php`.
  118. //
  119. // Capture groups:
  120. //
  121. // 1. An attribute name, that corresponds to...
  122. // 2. a value in double quotes.
  123. // 3. An attribute name, that corresponds to...
  124. // 4. a value in single quotes.
  125. // 5. An attribute name, that corresponds to...
  126. // 6. an unquoted value.
  127. // 7. A numeric attribute in double quotes.
  128. // 8. A numeric attribute in single quotes.
  129. // 9. An unquoted numeric attribute.
  130. pattern = /([\w-]+)\s*=\s*"([^"]*)"(?:\s|$)|([\w-]+)\s*=\s*'([^']*)'(?:\s|$)|([\w-]+)\s*=\s*([^\s'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|'([^']*)'(?:\s|$)|(\S+)(?:\s|$)/g;
  131. // Map zero-width spaces to actual spaces.
  132. text = text.replace( /[\u00a0\u200b]/g, ' ' );
  133. // Match and normalize attributes.
  134. while ( (match = pattern.exec( text )) ) {
  135. if ( match[1] ) {
  136. named[ match[1].toLowerCase() ] = match[2];
  137. } else if ( match[3] ) {
  138. named[ match[3].toLowerCase() ] = match[4];
  139. } else if ( match[5] ) {
  140. named[ match[5].toLowerCase() ] = match[6];
  141. } else if ( match[7] ) {
  142. numeric.push( match[7] );
  143. } else if ( match[8] ) {
  144. numeric.push( match[8] );
  145. } else if ( match[9] ) {
  146. numeric.push( match[9] );
  147. }
  148. }
  149. return {
  150. named: named,
  151. numeric: numeric
  152. };
  153. }),
  154. // ### Generate a Shortcode Object from a RegExp match
  155. // Accepts a `match` object from calling `regexp.exec()` on a `RegExp`
  156. // generated by `wp.shortcode.regexp()`. `match` can also be set to the
  157. // `arguments` from a callback passed to `regexp.replace()`.
  158. fromMatch: function( match ) {
  159. var type;
  160. if ( match[4] ) {
  161. type = 'self-closing';
  162. } else if ( match[6] ) {
  163. type = 'closed';
  164. } else {
  165. type = 'single';
  166. }
  167. return new wp.shortcode({
  168. tag: match[2],
  169. attrs: match[3],
  170. type: type,
  171. content: match[5]
  172. });
  173. }
  174. };
  175. // Shortcode Objects
  176. // -----------------
  177. //
  178. // Shortcode objects are generated automatically when using the main
  179. // `wp.shortcode` methods: `next()`, `replace()`, and `string()`.
  180. //
  181. // To access a raw representation of a shortcode, pass an `options` object,
  182. // containing a `tag` string, a string or object of `attrs`, a string
  183. // indicating the `type` of the shortcode ('single', 'self-closing', or
  184. // 'closed'), and a `content` string.
  185. wp.shortcode = _.extend( function( options ) {
  186. _.extend( this, _.pick( options || {}, 'tag', 'attrs', 'type', 'content' ) );
  187. var attrs = this.attrs;
  188. // Ensure we have a correctly formatted `attrs` object.
  189. this.attrs = {
  190. named: {},
  191. numeric: []
  192. };
  193. if ( ! attrs ) {
  194. return;
  195. }
  196. // Parse a string of attributes.
  197. if ( _.isString( attrs ) ) {
  198. this.attrs = wp.shortcode.attrs( attrs );
  199. // Identify a correctly formatted `attrs` object.
  200. } else if ( _.isEqual( _.keys( attrs ), [ 'named', 'numeric' ] ) ) {
  201. this.attrs = attrs;
  202. // Handle a flat object of attributes.
  203. } else {
  204. _.each( options.attrs, function( value, key ) {
  205. this.set( key, value );
  206. }, this );
  207. }
  208. }, wp.shortcode );
  209. _.extend( wp.shortcode.prototype, {
  210. // ### Get a shortcode attribute
  211. //
  212. // Automatically detects whether `attr` is named or numeric and routes
  213. // it accordingly.
  214. get: function( attr ) {
  215. return this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ];
  216. },
  217. // ### Set a shortcode attribute
  218. //
  219. // Automatically detects whether `attr` is named or numeric and routes
  220. // it accordingly.
  221. set: function( attr, value ) {
  222. this.attrs[ _.isNumber( attr ) ? 'numeric' : 'named' ][ attr ] = value;
  223. return this;
  224. },
  225. // ### Transform the shortcode match into a string
  226. string: function() {
  227. var text = '[' + this.tag;
  228. _.each( this.attrs.numeric, function( value ) {
  229. if ( /\s/.test( value ) ) {
  230. text += ' "' + value + '"';
  231. } else {
  232. text += ' ' + value;
  233. }
  234. });
  235. _.each( this.attrs.named, function( value, name ) {
  236. text += ' ' + name + '="' + value + '"';
  237. });
  238. // If the tag is marked as `single` or `self-closing`, close the
  239. // tag and ignore any additional content.
  240. if ( 'single' === this.type ) {
  241. return text + ']';
  242. } else if ( 'self-closing' === this.type ) {
  243. return text + ' /]';
  244. }
  245. // Complete the opening tag.
  246. text += ']';
  247. if ( this.content ) {
  248. text += this.content;
  249. }
  250. // Add the closing tag.
  251. return text + '[/' + this.tag + ']';
  252. }
  253. });
  254. }());
  255. // HTML utility functions
  256. // ----------------------
  257. //
  258. // Experimental. These functions may change or be removed in the future.
  259. (function(){
  260. wp.html = _.extend( wp.html || {}, {
  261. // ### Parse HTML attributes.
  262. //
  263. // Converts `content` to a set of parsed HTML attributes.
  264. // Utilizes `wp.shortcode.attrs( content )`, which is a valid superset of
  265. // the HTML attribute specification. Reformats the attributes into an
  266. // object that contains the `attrs` with `key:value` mapping, and a record
  267. // of the attributes that were entered using `empty` attribute syntax (i.e.
  268. // with no value).
  269. attrs: function( content ) {
  270. var result, attrs;
  271. // If `content` ends in a slash, strip it.
  272. if ( '/' === content[ content.length - 1 ] ) {
  273. content = content.slice( 0, -1 );
  274. }
  275. result = wp.shortcode.attrs( content );
  276. attrs = result.named;
  277. _.each( result.numeric, function( key ) {
  278. if ( /\s/.test( key ) ) {
  279. return;
  280. }
  281. attrs[ key ] = '';
  282. });
  283. return attrs;
  284. },
  285. // ### Convert an HTML-representation of an object to a string.
  286. string: function( options ) {
  287. var text = '<' + options.tag,
  288. content = options.content || '';
  289. _.each( options.attrs, function( value, attr ) {
  290. text += ' ' + attr;
  291. // Convert boolean values to strings.
  292. if ( _.isBoolean( value ) ) {
  293. value = value ? 'true' : 'false';
  294. }
  295. text += '="' + value + '"';
  296. });
  297. // Return the result if it is a self-closing tag.
  298. if ( options.single ) {
  299. return text + ' />';
  300. }
  301. // Complete the opening tag.
  302. text += '>';
  303. // If `content` is an object, recursively call this function.
  304. text += _.isObject( content ) ? wp.html.string( content ) : content;
  305. return text + '</' + options.tag + '>';
  306. }
  307. });
  308. }());