Нет описания

autop.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. this["wp"] = this["wp"] || {}; this["wp"]["autop"] =
  2. /******/ (function(modules) { // webpackBootstrap
  3. /******/ // The module cache
  4. /******/ var installedModules = {};
  5. /******/
  6. /******/ // The require function
  7. /******/ function __webpack_require__(moduleId) {
  8. /******/
  9. /******/ // Check if module is in cache
  10. /******/ if(installedModules[moduleId]) {
  11. /******/ return installedModules[moduleId].exports;
  12. /******/ }
  13. /******/ // Create a new module (and put it into the cache)
  14. /******/ var module = installedModules[moduleId] = {
  15. /******/ i: moduleId,
  16. /******/ l: false,
  17. /******/ exports: {}
  18. /******/ };
  19. /******/
  20. /******/ // Execute the module function
  21. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  22. /******/
  23. /******/ // Flag the module as loaded
  24. /******/ module.l = true;
  25. /******/
  26. /******/ // Return the exports of the module
  27. /******/ return module.exports;
  28. /******/ }
  29. /******/
  30. /******/
  31. /******/ // expose the modules object (__webpack_modules__)
  32. /******/ __webpack_require__.m = modules;
  33. /******/
  34. /******/ // expose the module cache
  35. /******/ __webpack_require__.c = installedModules;
  36. /******/
  37. /******/ // define getter function for harmony exports
  38. /******/ __webpack_require__.d = function(exports, name, getter) {
  39. /******/ if(!__webpack_require__.o(exports, name)) {
  40. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  41. /******/ }
  42. /******/ };
  43. /******/
  44. /******/ // define __esModule on exports
  45. /******/ __webpack_require__.r = function(exports) {
  46. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  47. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  48. /******/ }
  49. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  50. /******/ };
  51. /******/
  52. /******/ // create a fake namespace object
  53. /******/ // mode & 1: value is a module id, require it
  54. /******/ // mode & 2: merge all properties of value into the ns
  55. /******/ // mode & 4: return value when already ns object
  56. /******/ // mode & 8|1: behave like require
  57. /******/ __webpack_require__.t = function(value, mode) {
  58. /******/ if(mode & 1) value = __webpack_require__(value);
  59. /******/ if(mode & 8) return value;
  60. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  61. /******/ var ns = Object.create(null);
  62. /******/ __webpack_require__.r(ns);
  63. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  64. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  65. /******/ return ns;
  66. /******/ };
  67. /******/
  68. /******/ // getDefaultExport function for compatibility with non-harmony modules
  69. /******/ __webpack_require__.n = function(module) {
  70. /******/ var getter = module && module.__esModule ?
  71. /******/ function getDefault() { return module['default']; } :
  72. /******/ function getModuleExports() { return module; };
  73. /******/ __webpack_require__.d(getter, 'a', getter);
  74. /******/ return getter;
  75. /******/ };
  76. /******/
  77. /******/ // Object.prototype.hasOwnProperty.call
  78. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  79. /******/
  80. /******/ // __webpack_public_path__
  81. /******/ __webpack_require__.p = "";
  82. /******/
  83. /******/
  84. /******/ // Load entry module and return exports
  85. /******/ return __webpack_require__(__webpack_require__.s = "zbAn");
  86. /******/ })
  87. /************************************************************************/
  88. /******/ ({
  89. /***/ "zbAn":
  90. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  91. "use strict";
  92. __webpack_require__.r(__webpack_exports__);
  93. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autop", function() { return autop; });
  94. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removep", function() { return removep; });
  95. /**
  96. * The regular expression for an HTML element.
  97. *
  98. * @type {RegExp}
  99. */
  100. const htmlSplitRegex = (() => {
  101. /* eslint-disable no-multi-spaces */
  102. const comments = '!' + // Start of comment, after the <.
  103. '(?:' + // Unroll the loop: Consume everything until --> is found.
  104. '-(?!->)' + // Dash not followed by end of comment.
  105. '[^\\-]*' + // Consume non-dashes.
  106. ')*' + // Loop possessively.
  107. '(?:-->)?'; // End of comment. If not found, match all input.
  108. const cdata = '!\\[CDATA\\[' + // Start of comment, after the <.
  109. '[^\\]]*' + // Consume non-].
  110. '(?:' + // Unroll the loop: Consume everything until ]]> is found.
  111. '](?!]>)' + // One ] not followed by end of comment.
  112. '[^\\]]*' + // Consume non-].
  113. ')*?' + // Loop possessively.
  114. '(?:]]>)?'; // End of comment. If not found, match all input.
  115. const escaped = '(?=' + // Is the element escaped?
  116. '!--' + '|' + '!\\[CDATA\\[' + ')' + '((?=!-)' + // If yes, which type?
  117. comments + '|' + cdata + ')';
  118. const regex = '(' + // Capture the entire match.
  119. '<' + // Find start of element.
  120. '(' + // Conditional expression follows.
  121. escaped + // Find end of escaped element.
  122. '|' + // ... else ...
  123. '[^>]*>?' + // Find end of normal element.
  124. ')' + ')';
  125. return new RegExp(regex);
  126. /* eslint-enable no-multi-spaces */
  127. })();
  128. /**
  129. * Separate HTML elements and comments from the text.
  130. *
  131. * @param {string} input The text which has to be formatted.
  132. * @return {string[]} The formatted text.
  133. */
  134. function htmlSplit(input) {
  135. const parts = [];
  136. let workingInput = input;
  137. let match;
  138. while (match = workingInput.match(htmlSplitRegex)) {
  139. // The `match` result, when invoked on a RegExp with the `g` flag (`/foo/g`) will not include `index`.
  140. // If the `g` flag is omitted, `index` is included.
  141. // `htmlSplitRegex` does not have the `g` flag so we can assert it will have an index number.
  142. // Assert `match.index` is a number.
  143. const index =
  144. /** @type {number} */
  145. match.index;
  146. parts.push(workingInput.slice(0, index));
  147. parts.push(match[0]);
  148. workingInput = workingInput.slice(index + match[0].length);
  149. }
  150. if (workingInput.length) {
  151. parts.push(workingInput);
  152. }
  153. return parts;
  154. }
  155. /**
  156. * Replace characters or phrases within HTML elements only.
  157. *
  158. * @param {string} haystack The text which has to be formatted.
  159. * @param {Record<string,string>} replacePairs In the form {from: 'to', …}.
  160. * @return {string} The formatted text.
  161. */
  162. function replaceInHtmlTags(haystack, replacePairs) {
  163. // Find all elements.
  164. const textArr = htmlSplit(haystack);
  165. let changed = false; // Extract all needles.
  166. const needles = Object.keys(replacePairs); // Loop through delimiters (elements) only.
  167. for (let i = 1; i < textArr.length; i += 2) {
  168. for (let j = 0; j < needles.length; j++) {
  169. const needle = needles[j];
  170. if (-1 !== textArr[i].indexOf(needle)) {
  171. textArr[i] = textArr[i].replace(new RegExp(needle, 'g'), replacePairs[needle]);
  172. changed = true; // After one strtr() break out of the foreach loop and look at next element.
  173. break;
  174. }
  175. }
  176. }
  177. if (changed) {
  178. haystack = textArr.join('');
  179. }
  180. return haystack;
  181. }
  182. /**
  183. * Replaces double line-breaks with paragraph elements.
  184. *
  185. * A group of regex replaces used to identify text formatted with newlines and
  186. * replace double line-breaks with HTML paragraph tags. The remaining line-
  187. * breaks after conversion become `<br />` tags, unless br is set to 'false'.
  188. *
  189. * @param {string} text The text which has to be formatted.
  190. * @param {boolean} br Optional. If set, will convert all remaining line-
  191. * breaks after paragraphing. Default true.
  192. *
  193. * @example
  194. *```js
  195. * import { autop } from '@wordpress/autop';
  196. * autop( 'my text' ); // "<p>my text</p>"
  197. * ```
  198. *
  199. * @return {string} Text which has been converted into paragraph tags.
  200. */
  201. function autop(text, br = true) {
  202. const preTags = [];
  203. if (text.trim() === '') {
  204. return '';
  205. } // Just to make things a little easier, pad the end.
  206. text = text + '\n';
  207. /*
  208. * Pre tags shouldn't be touched by autop.
  209. * Replace pre tags with placeholders and bring them back after autop.
  210. */
  211. if (text.indexOf('<pre') !== -1) {
  212. const textParts = text.split('</pre>');
  213. const lastText = textParts.pop();
  214. text = '';
  215. for (let i = 0; i < textParts.length; i++) {
  216. const textPart = textParts[i];
  217. const start = textPart.indexOf('<pre'); // Malformed html?
  218. if (start === -1) {
  219. text += textPart;
  220. continue;
  221. }
  222. const name = '<pre wp-pre-tag-' + i + '></pre>';
  223. preTags.push([name, textPart.substr(start) + '</pre>']);
  224. text += textPart.substr(0, start) + name;
  225. }
  226. text += lastText;
  227. } // Change multiple <br>s into two line breaks, which will turn into paragraphs.
  228. text = text.replace(/<br\s*\/?>\s*<br\s*\/?>/g, '\n\n');
  229. const allBlocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; // Add a double line break above block-level opening tags.
  230. text = text.replace(new RegExp('(<' + allBlocks + '[\\s/>])', 'g'), '\n\n$1'); // Add a double line break below block-level closing tags.
  231. text = text.replace(new RegExp('(</' + allBlocks + '>)', 'g'), '$1\n\n'); // Standardize newline characters to "\n".
  232. text = text.replace(/\r\n|\r/g, '\n'); // Find newlines in all elements and add placeholders.
  233. text = replaceInHtmlTags(text, {
  234. '\n': ' <!-- wpnl --> '
  235. }); // Collapse line breaks before and after <option> elements so they don't get autop'd.
  236. if (text.indexOf('<option') !== -1) {
  237. text = text.replace(/\s*<option/g, '<option');
  238. text = text.replace(/<\/option>\s*/g, '</option>');
  239. }
  240. /*
  241. * Collapse line breaks inside <object> elements, before <param> and <embed> elements
  242. * so they don't get autop'd.
  243. */
  244. if (text.indexOf('</object>') !== -1) {
  245. text = text.replace(/(<object[^>]*>)\s*/g, '$1');
  246. text = text.replace(/\s*<\/object>/g, '</object>');
  247. text = text.replace(/\s*(<\/?(?:param|embed)[^>]*>)\s*/g, '$1');
  248. }
  249. /*
  250. * Collapse line breaks inside <audio> and <video> elements,
  251. * before and after <source> and <track> elements.
  252. */
  253. if (text.indexOf('<source') !== -1 || text.indexOf('<track') !== -1) {
  254. text = text.replace(/([<\[](?:audio|video)[^>\]]*[>\]])\s*/g, '$1');
  255. text = text.replace(/\s*([<\[]\/(?:audio|video)[>\]])/g, '$1');
  256. text = text.replace(/\s*(<(?:source|track)[^>]*>)\s*/g, '$1');
  257. } // Collapse line breaks before and after <figcaption> elements.
  258. if (text.indexOf('<figcaption') !== -1) {
  259. text = text.replace(/\s*(<figcaption[^>]*>)/, '$1');
  260. text = text.replace(/<\/figcaption>\s*/, '</figcaption>');
  261. } // Remove more than two contiguous line breaks.
  262. text = text.replace(/\n\n+/g, '\n\n'); // Split up the contents into an array of strings, separated by double line breaks.
  263. const texts = text.split(/\n\s*\n/).filter(Boolean); // Reset text prior to rebuilding.
  264. text = ''; // Rebuild the content as a string, wrapping every bit with a <p>.
  265. texts.forEach(textPiece => {
  266. text += '<p>' + textPiece.replace(/^\n*|\n*$/g, '') + '</p>\n';
  267. }); // Under certain strange conditions it could create a P of entirely whitespace.
  268. text = text.replace(/<p>\s*<\/p>/g, ''); // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
  269. text = text.replace(/<p>([^<]+)<\/(div|address|form)>/g, '<p>$1</p></$2>'); // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
  270. text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // In some cases <li> may get wrapped in <p>, fix them.
  271. text = text.replace(/<p>(<li.+?)<\/p>/g, '$1'); // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
  272. text = text.replace(/<p><blockquote([^>]*)>/gi, '<blockquote$1><p>');
  273. text = text.replace(/<\/blockquote><\/p>/g, '</p></blockquote>'); // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
  274. text = text.replace(new RegExp('<p>\\s*(</?' + allBlocks + '[^>]*>)', 'g'), '$1'); // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
  275. text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*</p>', 'g'), '$1'); // Optionally insert line breaks.
  276. if (br) {
  277. // Replace newlines that shouldn't be touched with a placeholder.
  278. text = text.replace(/<(script|style).*?<\/\\1>/g, match => match[0].replace(/\n/g, '<WPPreserveNewline />')); // Normalize <br>
  279. text = text.replace(/<br>|<br\/>/g, '<br />'); // Replace any new line characters that aren't preceded by a <br /> with a <br />.
  280. text = text.replace(/(<br \/>)?\s*\n/g, (a, b) => b ? a : '<br />\n'); // Replace newline placeholders with newlines.
  281. text = text.replace(/<WPPreserveNewline \/>/g, '\n');
  282. } // If a <br /> tag is after an opening or closing block tag, remove it.
  283. text = text.replace(new RegExp('(</?' + allBlocks + '[^>]*>)\\s*<br />', 'g'), '$1'); // If a <br /> tag is before a subset of opening or closing block tags, remove it.
  284. text = text.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)/g, '$1');
  285. text = text.replace(/\n<\/p>$/g, '</p>'); // Replace placeholder <pre> tags with their original content.
  286. preTags.forEach(preTag => {
  287. const [name, original] = preTag;
  288. text = text.replace(name, original);
  289. }); // Restore newlines in all elements.
  290. if (-1 !== text.indexOf('<!-- wpnl -->')) {
  291. text = text.replace(/\s?<!-- wpnl -->\s?/g, '\n');
  292. }
  293. return text;
  294. }
  295. /**
  296. * Replaces `<p>` tags with two line breaks. "Opposite" of autop().
  297. *
  298. * Replaces `<p>` tags with two line breaks except where the `<p>` has attributes.
  299. * Unifies whitespace. Indents `<li>`, `<dt>` and `<dd>` for better readability.
  300. *
  301. * @param {string} html The content from the editor.
  302. *
  303. * @example
  304. * ```js
  305. * import { removep } from '@wordpress/autop';
  306. * removep( '<p>my text</p>' ); // "my text"
  307. * ```
  308. *
  309. * @return {string} The content with stripped paragraph tags.
  310. */
  311. function removep(html) {
  312. const blocklist = 'blockquote|ul|ol|li|dl|dt|dd|table|thead|tbody|tfoot|tr|th|td|h[1-6]|fieldset|figure';
  313. const blocklist1 = blocklist + '|div|p';
  314. const blocklist2 = blocklist + '|pre';
  315. /** @type {string[]} */
  316. const preserve = [];
  317. let preserveLinebreaks = false;
  318. let preserveBr = false;
  319. if (!html) {
  320. return '';
  321. } // Protect script and style tags.
  322. if (html.indexOf('<script') !== -1 || html.indexOf('<style') !== -1) {
  323. html = html.replace(/<(script|style)[^>]*>[\s\S]*?<\/\1>/g, match => {
  324. preserve.push(match);
  325. return '<wp-preserve>';
  326. });
  327. } // Protect pre tags.
  328. if (html.indexOf('<pre') !== -1) {
  329. preserveLinebreaks = true;
  330. html = html.replace(/<pre[^>]*>[\s\S]+?<\/pre>/g, a => {
  331. a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp-line-break>');
  332. a = a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-line-break>');
  333. return a.replace(/\r?\n/g, '<wp-line-break>');
  334. });
  335. } // Remove line breaks but keep <br> tags inside image captions.
  336. if (html.indexOf('[caption') !== -1) {
  337. preserveBr = true;
  338. html = html.replace(/\[caption[\s\S]+?\[\/caption\]/g, a => {
  339. return a.replace(/<br([^>]*)>/g, '<wp-temp-br$1>').replace(/[\r\n\t]+/, '');
  340. });
  341. } // Normalize white space characters before and after block tags.
  342. html = html.replace(new RegExp('\\s*</(' + blocklist1 + ')>\\s*', 'g'), '</$1>\n');
  343. html = html.replace(new RegExp('\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g'), '\n<$1>'); // Mark </p> if it has any attributes.
  344. html = html.replace(/(<p [^>]+>[\s\S]*?)<\/p>/g, '$1</p#>'); // Preserve the first <p> inside a <div>.
  345. html = html.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n'); // Remove paragraph tags.
  346. html = html.replace(/\s*<p>/gi, '');
  347. html = html.replace(/\s*<\/p>\s*/gi, '\n\n'); // Normalize white space chars and remove multiple line breaks.
  348. html = html.replace(/\n[\s\u00a0]+\n/g, '\n\n'); // Replace <br> tags with line breaks.
  349. html = html.replace(/(\s*)<br ?\/?>\s*/gi, (_, space) => {
  350. if (space && space.indexOf('\n') !== -1) {
  351. return '\n\n';
  352. }
  353. return '\n';
  354. }); // Fix line breaks around <div>.
  355. html = html.replace(/\s*<div/g, '\n<div');
  356. html = html.replace(/<\/div>\s*/g, '</div>\n'); // Fix line breaks around caption shortcodes.
  357. html = html.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
  358. html = html.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption'); // Pad block elements tags with a line break.
  359. html = html.replace(new RegExp('\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
  360. html = html.replace(new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g'), '</$1>\n'); // Indent <li>, <dt> and <dd> tags.
  361. html = html.replace(/<((li|dt|dd)[^>]*)>/g, ' \t<$1>'); // Fix line breaks around <select> and <option>.
  362. if (html.indexOf('<option') !== -1) {
  363. html = html.replace(/\s*<option/g, '\n<option');
  364. html = html.replace(/\s*<\/select>/g, '\n</select>');
  365. } // Pad <hr> with two line breaks.
  366. if (html.indexOf('<hr') !== -1) {
  367. html = html.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
  368. } // Remove line breaks in <object> tags.
  369. if (html.indexOf('<object') !== -1) {
  370. html = html.replace(/<object[\s\S]+?<\/object>/g, a => {
  371. return a.replace(/[\r\n]+/g, '');
  372. });
  373. } // Unmark special paragraph closing tags.
  374. html = html.replace(/<\/p#>/g, '</p>\n'); // Pad remaining <p> tags whit a line break.
  375. html = html.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1'); // Trim.
  376. html = html.replace(/^\s+/, '');
  377. html = html.replace(/[\s\u00a0]+$/, '');
  378. if (preserveLinebreaks) {
  379. html = html.replace(/<wp-line-break>/g, '\n');
  380. }
  381. if (preserveBr) {
  382. html = html.replace(/<wp-temp-br([^>]*)>/g, '<br$1>');
  383. } // Restore preserved tags.
  384. if (preserve.length) {
  385. html = html.replace(/<wp-preserve>/g, () => {
  386. return (
  387. /** @type {string} */
  388. preserve.shift()
  389. );
  390. });
  391. }
  392. return html;
  393. }
  394. /***/ })
  395. /******/ });