plugin.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. ( function( tinymce ) {
  2. tinymce.ui.Factory.add( 'WPLinkPreview', tinymce.ui.Control.extend( {
  3. url: '#',
  4. renderHtml: function() {
  5. return (
  6. '<div id="' + this._id + '" class="wp-link-preview">' +
  7. '<a href="' + this.url + '" target="_blank" rel="noopener" tabindex="-1">' + this.url + '</a>' +
  8. '</div>'
  9. );
  10. },
  11. setURL: function( url ) {
  12. var index, lastIndex;
  13. if ( this.url !== url ) {
  14. this.url = url;
  15. url = window.decodeURIComponent( url );
  16. url = url.replace( /^(?:https?:)?\/\/(?:www\.)?/, '' );
  17. if ( ( index = url.indexOf( '?' ) ) !== -1 ) {
  18. url = url.slice( 0, index );
  19. }
  20. if ( ( index = url.indexOf( '#' ) ) !== -1 ) {
  21. url = url.slice( 0, index );
  22. }
  23. url = url.replace( /(?:index)?\.html$/, '' );
  24. if ( url.charAt( url.length - 1 ) === '/' ) {
  25. url = url.slice( 0, -1 );
  26. }
  27. // If nothing's left (maybe the URL was just a fragment), use the whole URL.
  28. if ( url === '' ) {
  29. url = this.url;
  30. }
  31. // If the URL is longer that 40 chars, concatenate the beginning (after the domain) and ending with ...
  32. if ( url.length > 40 && ( index = url.indexOf( '/' ) ) !== -1 && ( lastIndex = url.lastIndexOf( '/' ) ) !== -1 && lastIndex !== index ) {
  33. // If the beginning + ending are shorter that 40 chars, show more of the ending
  34. if ( index + url.length - lastIndex < 40 ) {
  35. lastIndex = -( 40 - ( index + 1 ) );
  36. }
  37. url = url.slice( 0, index + 1 ) + '\u2026' + url.slice( lastIndex );
  38. }
  39. tinymce.$( this.getEl().firstChild ).attr( 'href', this.url ).text( url );
  40. }
  41. }
  42. } ) );
  43. tinymce.ui.Factory.add( 'WPLinkInput', tinymce.ui.Control.extend( {
  44. renderHtml: function() {
  45. return (
  46. '<div id="' + this._id + '" class="wp-link-input">' +
  47. '<input type="text" value="" placeholder="' + tinymce.translate( 'Paste URL or type to search' ) + '" />' +
  48. '<input type="text" style="display:none" value="" />' +
  49. '</div>'
  50. );
  51. },
  52. setURL: function( url ) {
  53. this.getEl().firstChild.value = url;
  54. },
  55. getURL: function() {
  56. return tinymce.trim( this.getEl().firstChild.value );
  57. },
  58. getLinkText: function() {
  59. var text = this.getEl().firstChild.nextSibling.value;
  60. if ( ! tinymce.trim( text ) ) {
  61. return '';
  62. }
  63. return text.replace( /[\r\n\t ]+/g, ' ' );
  64. },
  65. reset: function() {
  66. var urlInput = this.getEl().firstChild;
  67. urlInput.value = '';
  68. urlInput.nextSibling.value = '';
  69. }
  70. } ) );
  71. tinymce.PluginManager.add( 'wplink', function( editor ) {
  72. var toolbar;
  73. var editToolbar;
  74. var previewInstance;
  75. var inputInstance;
  76. var linkNode;
  77. var doingUndoRedo;
  78. var doingUndoRedoTimer;
  79. var $ = window.jQuery;
  80. var emailRegex = /^(mailto:)?[a-z0-9._%+-]+@[a-z0-9][a-z0-9.-]*\.[a-z]{2,63}$/i;
  81. var urlRegex1 = /^https?:\/\/([^\s/?.#-][^\s\/?.#]*\.?)+(\/[^\s"]*)?$/i;
  82. var urlRegex2 = /^https?:\/\/[^\/]+\.[^\/]+($|\/)/i;
  83. var speak = ( typeof window.wp !== 'undefined' && window.wp.a11y && window.wp.a11y.speak ) ? window.wp.a11y.speak : function() {};
  84. var hasLinkError = false;
  85. function getSelectedLink() {
  86. var href, html,
  87. node = editor.selection.getStart(),
  88. link = editor.dom.getParent( node, 'a[href]' );
  89. if ( ! link ) {
  90. html = editor.selection.getContent({ format: 'raw' });
  91. if ( html && html.indexOf( '</a>' ) !== -1 ) {
  92. href = html.match( /href="([^">]+)"/ );
  93. if ( href && href[1] ) {
  94. link = editor.$( 'a[href="' + href[1] + '"]', node )[0];
  95. }
  96. if ( link ) {
  97. editor.selection.select( link );
  98. }
  99. }
  100. }
  101. return link;
  102. }
  103. function removePlaceholders() {
  104. editor.$( 'a' ).each( function( i, element ) {
  105. var $element = editor.$( element );
  106. if ( $element.attr( 'href' ) === '_wp_link_placeholder' ) {
  107. editor.dom.remove( element, true );
  108. } else if ( $element.attr( 'data-wplink-edit' ) ) {
  109. $element.attr( 'data-wplink-edit', null );
  110. }
  111. });
  112. }
  113. function removePlaceholderStrings( content, dataAttr ) {
  114. return content.replace( /(<a [^>]+>)([\s\S]*?)<\/a>/g, function( all, tag, text ) {
  115. if ( tag.indexOf( ' href="_wp_link_placeholder"' ) > -1 ) {
  116. return text;
  117. }
  118. if ( dataAttr ) {
  119. tag = tag.replace( / data-wplink-edit="true"/g, '' );
  120. }
  121. tag = tag.replace( / data-wplink-url-error="true"/g, '' );
  122. return tag + text + '</a>';
  123. });
  124. }
  125. function checkLink( node ) {
  126. var $link = editor.$( node );
  127. var href = $link.attr( 'href' );
  128. if ( ! href || typeof $ === 'undefined' ) {
  129. return;
  130. }
  131. hasLinkError = false;
  132. if ( /^http/i.test( href ) && ( ! urlRegex1.test( href ) || ! urlRegex2.test( href ) ) ) {
  133. hasLinkError = true;
  134. $link.attr( 'data-wplink-url-error', 'true' );
  135. speak( editor.translate( 'Warning: the link has been inserted but may have errors. Please test it.' ), 'assertive' );
  136. } else {
  137. $link.removeAttr( 'data-wplink-url-error' );
  138. }
  139. }
  140. editor.on( 'preinit', function() {
  141. if ( editor.wp && editor.wp._createToolbar ) {
  142. toolbar = editor.wp._createToolbar( [
  143. 'wp_link_preview',
  144. 'wp_link_edit',
  145. 'wp_link_remove'
  146. ], true );
  147. var editButtons = [
  148. 'wp_link_input',
  149. 'wp_link_apply'
  150. ];
  151. if ( typeof window.wpLink !== 'undefined' ) {
  152. editButtons.push( 'wp_link_advanced' );
  153. }
  154. editToolbar = editor.wp._createToolbar( editButtons, true );
  155. editToolbar.on( 'show', function() {
  156. if ( typeof window.wpLink === 'undefined' || ! window.wpLink.modalOpen ) {
  157. window.setTimeout( function() {
  158. var element = editToolbar.$el.find( 'input.ui-autocomplete-input' )[0],
  159. selection = linkNode && ( linkNode.textContent || linkNode.innerText );
  160. if ( element ) {
  161. if ( ! element.value && selection && typeof window.wpLink !== 'undefined' ) {
  162. element.value = window.wpLink.getUrlFromSelection( selection );
  163. }
  164. if ( ! doingUndoRedo ) {
  165. element.focus();
  166. element.select();
  167. }
  168. }
  169. } );
  170. }
  171. } );
  172. editToolbar.on( 'hide', function() {
  173. if ( ! editToolbar.scrolling ) {
  174. editor.execCommand( 'wp_link_cancel' );
  175. }
  176. } );
  177. }
  178. } );
  179. editor.addCommand( 'WP_Link', function() {
  180. if ( tinymce.Env.ie && tinymce.Env.ie < 10 && typeof window.wpLink !== 'undefined' ) {
  181. window.wpLink.open( editor.id );
  182. return;
  183. }
  184. linkNode = getSelectedLink();
  185. editToolbar.tempHide = false;
  186. if ( linkNode ) {
  187. editor.dom.setAttribs( linkNode, { 'data-wplink-edit': true } );
  188. } else {
  189. removePlaceholders();
  190. editor.execCommand( 'mceInsertLink', false, { href: '_wp_link_placeholder' } );
  191. linkNode = editor.$( 'a[href="_wp_link_placeholder"]' )[0];
  192. editor.nodeChanged();
  193. }
  194. } );
  195. editor.addCommand( 'wp_link_apply', function() {
  196. if ( editToolbar.scrolling ) {
  197. return;
  198. }
  199. var href, text;
  200. if ( linkNode ) {
  201. href = inputInstance.getURL();
  202. text = inputInstance.getLinkText();
  203. editor.focus();
  204. var parser = document.createElement( 'a' );
  205. parser.href = href;
  206. if ( 'javascript:' === parser.protocol || 'data:' === parser.protocol ) { // jshint ignore:line
  207. href = '';
  208. }
  209. if ( ! href ) {
  210. editor.dom.remove( linkNode, true );
  211. return;
  212. }
  213. if ( ! /^(?:[a-z]+:|#|\?|\.|\/)/.test( href ) && ! emailRegex.test( href ) ) {
  214. href = 'http://' + href;
  215. }
  216. editor.dom.setAttribs( linkNode, { href: href, 'data-wplink-edit': null } );
  217. if ( ! tinymce.trim( linkNode.innerHTML ) ) {
  218. editor.$( linkNode ).text( text || href );
  219. }
  220. checkLink( linkNode );
  221. }
  222. inputInstance.reset();
  223. editor.nodeChanged();
  224. // Audible confirmation message when a link has been inserted in the Editor.
  225. if ( typeof window.wpLinkL10n !== 'undefined' && ! hasLinkError ) {
  226. speak( window.wpLinkL10n.linkInserted );
  227. }
  228. } );
  229. editor.addCommand( 'wp_link_cancel', function() {
  230. if ( ! editToolbar.tempHide ) {
  231. inputInstance.reset();
  232. removePlaceholders();
  233. }
  234. } );
  235. editor.addCommand( 'wp_unlink', function() {
  236. editor.execCommand( 'unlink' );
  237. editToolbar.tempHide = false;
  238. editor.execCommand( 'wp_link_cancel' );
  239. } );
  240. // WP default shortcuts
  241. editor.addShortcut( 'access+a', '', 'WP_Link' );
  242. editor.addShortcut( 'access+s', '', 'wp_unlink' );
  243. // The "de-facto standard" shortcut, see #27305
  244. editor.addShortcut( 'meta+k', '', 'WP_Link' );
  245. editor.addButton( 'link', {
  246. icon: 'link',
  247. tooltip: 'Insert/edit link',
  248. cmd: 'WP_Link',
  249. stateSelector: 'a[href]'
  250. });
  251. editor.addButton( 'unlink', {
  252. icon: 'unlink',
  253. tooltip: 'Remove link',
  254. cmd: 'unlink'
  255. });
  256. editor.addMenuItem( 'link', {
  257. icon: 'link',
  258. text: 'Insert/edit link',
  259. cmd: 'WP_Link',
  260. stateSelector: 'a[href]',
  261. context: 'insert',
  262. prependToContext: true
  263. });
  264. editor.on( 'pastepreprocess', function( event ) {
  265. var pastedStr = event.content,
  266. regExp = /^(?:https?:)?\/\/\S+$/i;
  267. if ( ! editor.selection.isCollapsed() && ! regExp.test( editor.selection.getContent() ) ) {
  268. pastedStr = pastedStr.replace( /<[^>]+>/g, '' );
  269. pastedStr = tinymce.trim( pastedStr );
  270. if ( regExp.test( pastedStr ) ) {
  271. editor.execCommand( 'mceInsertLink', false, {
  272. href: editor.dom.decode( pastedStr )
  273. } );
  274. event.preventDefault();
  275. }
  276. }
  277. } );
  278. // Remove any remaining placeholders on saving.
  279. editor.on( 'savecontent', function( event ) {
  280. event.content = removePlaceholderStrings( event.content, true );
  281. });
  282. // Prevent adding undo levels on inserting link placeholder.
  283. editor.on( 'BeforeAddUndo', function( event ) {
  284. if ( event.lastLevel && event.lastLevel.content && event.level.content &&
  285. event.lastLevel.content === removePlaceholderStrings( event.level.content ) ) {
  286. event.preventDefault();
  287. }
  288. });
  289. // When doing undo and redo with keyboard shortcuts (Ctrl|Cmd+Z, Ctrl|Cmd+Shift+Z, Ctrl|Cmd+Y),
  290. // set a flag to not focus the inline dialog. The editor has to remain focused so the users can do consecutive undo/redo.
  291. editor.on( 'keydown', function( event ) {
  292. if ( event.keyCode === 27 ) { // Esc
  293. editor.execCommand( 'wp_link_cancel' );
  294. }
  295. if ( event.altKey || ( tinymce.Env.mac && ( ! event.metaKey || event.ctrlKey ) ) ||
  296. ( ! tinymce.Env.mac && ! event.ctrlKey ) ) {
  297. return;
  298. }
  299. if ( event.keyCode === 89 || event.keyCode === 90 ) { // Y or Z
  300. doingUndoRedo = true;
  301. window.clearTimeout( doingUndoRedoTimer );
  302. doingUndoRedoTimer = window.setTimeout( function() {
  303. doingUndoRedo = false;
  304. }, 500 );
  305. }
  306. } );
  307. editor.addButton( 'wp_link_preview', {
  308. type: 'WPLinkPreview',
  309. onPostRender: function() {
  310. previewInstance = this;
  311. }
  312. } );
  313. editor.addButton( 'wp_link_input', {
  314. type: 'WPLinkInput',
  315. onPostRender: function() {
  316. var element = this.getEl(),
  317. input = element.firstChild,
  318. $input, cache, last;
  319. inputInstance = this;
  320. if ( $ && $.ui && $.ui.autocomplete ) {
  321. $input = $( input );
  322. $input.on( 'keydown', function() {
  323. $input.removeAttr( 'aria-activedescendant' );
  324. } )
  325. .autocomplete( {
  326. source: function( request, response ) {
  327. if ( last === request.term ) {
  328. response( cache );
  329. return;
  330. }
  331. if ( /^https?:/.test( request.term ) || request.term.indexOf( '.' ) !== -1 ) {
  332. return response();
  333. }
  334. $.post( window.ajaxurl, {
  335. action: 'wp-link-ajax',
  336. page: 1,
  337. search: request.term,
  338. _ajax_linking_nonce: $( '#_ajax_linking_nonce' ).val()
  339. }, function( data ) {
  340. cache = data;
  341. response( data );
  342. }, 'json' );
  343. last = request.term;
  344. },
  345. focus: function( event, ui ) {
  346. $input.attr( 'aria-activedescendant', 'mce-wp-autocomplete-' + ui.item.ID );
  347. /*
  348. * Don't empty the URL input field, when using the arrow keys to
  349. * highlight items. See api.jqueryui.com/autocomplete/#event-focus
  350. */
  351. event.preventDefault();
  352. },
  353. select: function( event, ui ) {
  354. $input.val( ui.item.permalink );
  355. $( element.firstChild.nextSibling ).val( ui.item.title );
  356. if ( 9 === event.keyCode && typeof window.wpLinkL10n !== 'undefined' ) {
  357. // Audible confirmation message when a link has been selected.
  358. speak( window.wpLinkL10n.linkSelected );
  359. }
  360. return false;
  361. },
  362. open: function() {
  363. $input.attr( 'aria-expanded', 'true' );
  364. editToolbar.blockHide = true;
  365. },
  366. close: function() {
  367. $input.attr( 'aria-expanded', 'false' );
  368. editToolbar.blockHide = false;
  369. },
  370. minLength: 2,
  371. position: {
  372. my: 'left top+2'
  373. },
  374. messages: {
  375. noResults: ( typeof window.uiAutocompleteL10n !== 'undefined' ) ? window.uiAutocompleteL10n.noResults : '',
  376. results: function( number ) {
  377. if ( typeof window.uiAutocompleteL10n !== 'undefined' ) {
  378. if ( number > 1 ) {
  379. return window.uiAutocompleteL10n.manyResults.replace( '%d', number );
  380. }
  381. return window.uiAutocompleteL10n.oneResult;
  382. }
  383. }
  384. }
  385. } ).autocomplete( 'instance' )._renderItem = function( ul, item ) {
  386. var fallbackTitle = ( typeof window.wpLinkL10n !== 'undefined' ) ? window.wpLinkL10n.noTitle : '',
  387. title = item.title ? item.title : fallbackTitle;
  388. return $( '<li role="option" id="mce-wp-autocomplete-' + item.ID + '">' )
  389. .append( '<span>' + title + '</span>&nbsp;<span class="wp-editor-float-right">' + item.info + '</span>' )
  390. .appendTo( ul );
  391. };
  392. $input.attr( {
  393. 'role': 'combobox',
  394. 'aria-autocomplete': 'list',
  395. 'aria-expanded': 'false',
  396. 'aria-owns': $input.autocomplete( 'widget' ).attr( 'id' )
  397. } )
  398. .on( 'focus', function() {
  399. var inputValue = $input.val();
  400. /*
  401. * Don't trigger a search if the URL field already has a link or is empty.
  402. * Also, avoids screen readers announce `No search results`.
  403. */
  404. if ( inputValue && ! /^https?:/.test( inputValue ) ) {
  405. $input.autocomplete( 'search' );
  406. }
  407. } )
  408. // Returns a jQuery object containing the menu element.
  409. .autocomplete( 'widget' )
  410. .addClass( 'wplink-autocomplete' )
  411. .attr( 'role', 'listbox' )
  412. .removeAttr( 'tabindex' ) // Remove the `tabindex=0` attribute added by jQuery UI.
  413. /*
  414. * Looks like Safari and VoiceOver need an `aria-selected` attribute. See ticket #33301.
  415. * The `menufocus` and `menublur` events are the same events used to add and remove
  416. * the `ui-state-focus` CSS class on the menu items. See jQuery UI Menu Widget.
  417. */
  418. .on( 'menufocus', function( event, ui ) {
  419. ui.item.attr( 'aria-selected', 'true' );
  420. })
  421. .on( 'menublur', function() {
  422. /*
  423. * The `menublur` event returns an object where the item is `null`
  424. * so we need to find the active item with other means.
  425. */
  426. $( this ).find( '[aria-selected="true"]' ).removeAttr( 'aria-selected' );
  427. });
  428. }
  429. tinymce.$( input ).on( 'keydown', function( event ) {
  430. if ( event.keyCode === 13 ) {
  431. editor.execCommand( 'wp_link_apply' );
  432. event.preventDefault();
  433. }
  434. } );
  435. }
  436. } );
  437. editor.on( 'wptoolbar', function( event ) {
  438. var linkNode = editor.dom.getParent( event.element, 'a' ),
  439. $linkNode, href, edit;
  440. if ( typeof window.wpLink !== 'undefined' && window.wpLink.modalOpen ) {
  441. editToolbar.tempHide = true;
  442. return;
  443. }
  444. editToolbar.tempHide = false;
  445. if ( linkNode ) {
  446. $linkNode = editor.$( linkNode );
  447. href = $linkNode.attr( 'href' );
  448. edit = $linkNode.attr( 'data-wplink-edit' );
  449. if ( href === '_wp_link_placeholder' || edit ) {
  450. if ( href !== '_wp_link_placeholder' && ! inputInstance.getURL() ) {
  451. inputInstance.setURL( href );
  452. }
  453. event.element = linkNode;
  454. event.toolbar = editToolbar;
  455. } else if ( href && ! $linkNode.find( 'img' ).length ) {
  456. previewInstance.setURL( href );
  457. event.element = linkNode;
  458. event.toolbar = toolbar;
  459. if ( $linkNode.attr( 'data-wplink-url-error' ) === 'true' ) {
  460. toolbar.$el.find( '.wp-link-preview a' ).addClass( 'wplink-url-error' );
  461. } else {
  462. toolbar.$el.find( '.wp-link-preview a' ).removeClass( 'wplink-url-error' );
  463. hasLinkError = false;
  464. }
  465. }
  466. } else if ( editToolbar.visible() ) {
  467. editor.execCommand( 'wp_link_cancel' );
  468. }
  469. } );
  470. editor.addButton( 'wp_link_edit', {
  471. tooltip: 'Edit|button', // '|button' is not displayed, only used for context
  472. icon: 'dashicon dashicons-edit',
  473. cmd: 'WP_Link'
  474. } );
  475. editor.addButton( 'wp_link_remove', {
  476. tooltip: 'Remove link',
  477. icon: 'dashicon dashicons-editor-unlink',
  478. cmd: 'wp_unlink'
  479. } );
  480. editor.addButton( 'wp_link_advanced', {
  481. tooltip: 'Link options',
  482. icon: 'dashicon dashicons-admin-generic',
  483. onclick: function() {
  484. if ( typeof window.wpLink !== 'undefined' ) {
  485. var url = inputInstance.getURL() || null,
  486. text = inputInstance.getLinkText() || null;
  487. /*
  488. * Accessibility note: moving focus back to the editor confuses
  489. * screen readers. They will announce again the Editor ARIA role
  490. * `application` and the iframe `title` attribute.
  491. *
  492. * Unfortunately IE looses the selection when the editor iframe
  493. * looses focus, so without returning focus to the editor, the code
  494. * in the modal will not be able to get the selection, place the caret
  495. * at the same location, etc.
  496. */
  497. if ( tinymce.Env.ie ) {
  498. editor.focus(); // Needed for IE
  499. }
  500. editToolbar.tempHide = true;
  501. window.wpLink.open( editor.id, url, text, linkNode );
  502. inputInstance.reset();
  503. }
  504. }
  505. } );
  506. editor.addButton( 'wp_link_apply', {
  507. tooltip: 'Apply',
  508. icon: 'dashicon dashicons-editor-break',
  509. cmd: 'wp_link_apply',
  510. classes: 'widget btn primary'
  511. } );
  512. return {
  513. close: function() {
  514. editToolbar.tempHide = false;
  515. editor.execCommand( 'wp_link_cancel' );
  516. },
  517. checkLink: checkLink
  518. };
  519. } );
  520. } )( window.tinymce );