Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 

352 Zeilen
10 KiB

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