plugin.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. removePlaceholders();
  188. editor.execCommand( 'mceInsertLink', false, { href: '_wp_link_placeholder' } );
  189. linkNode = editor.$( 'a[href="_wp_link_placeholder"]' )[0];
  190. editor.nodeChanged();
  191. }
  192. editor.dom.setAttribs( linkNode, { 'data-wplink-edit': true } );
  193. } );
  194. editor.addCommand( 'wp_link_apply', function() {
  195. if ( editToolbar.scrolling ) {
  196. return;
  197. }
  198. var href, text;
  199. if ( linkNode ) {
  200. href = inputInstance.getURL();
  201. text = inputInstance.getLinkText();
  202. editor.focus();
  203. var parser = document.createElement( 'a' );
  204. parser.href = href;
  205. if ( 'javascript:' === parser.protocol || 'data:' === parser.protocol ) { // jshint ignore:line
  206. href = '';
  207. }
  208. if ( ! href ) {
  209. editor.dom.remove( linkNode, true );
  210. return;
  211. }
  212. if ( ! /^(?:[a-z]+:|#|\?|\.|\/)/.test( href ) && ! emailRegex.test( href ) ) {
  213. href = 'http://' + href;
  214. }
  215. editor.dom.setAttribs( linkNode, { href: href, 'data-wplink-edit': null } );
  216. if ( ! tinymce.trim( linkNode.innerHTML ) ) {
  217. editor.$( linkNode ).text( text || href );
  218. }
  219. checkLink( linkNode );
  220. }
  221. inputInstance.reset();
  222. editor.nodeChanged();
  223. // Audible confirmation message when a link has been inserted in the Editor.
  224. if ( typeof window.wpLinkL10n !== 'undefined' && ! hasLinkError ) {
  225. speak( window.wpLinkL10n.linkInserted );
  226. }
  227. } );
  228. editor.addCommand( 'wp_link_cancel', function() {
  229. inputInstance.reset();
  230. if ( ! editToolbar.tempHide ) {
  231. removePlaceholders();
  232. }
  233. } );
  234. editor.addCommand( 'wp_unlink', function() {
  235. editor.execCommand( 'unlink' );
  236. editToolbar.tempHide = false;
  237. editor.execCommand( 'wp_link_cancel' );
  238. } );
  239. // WP default shortcuts
  240. editor.addShortcut( 'access+a', '', 'WP_Link' );
  241. editor.addShortcut( 'access+s', '', 'wp_unlink' );
  242. // The "de-facto standard" shortcut, see #27305
  243. editor.addShortcut( 'meta+k', '', 'WP_Link' );
  244. editor.addButton( 'link', {
  245. icon: 'link',
  246. tooltip: 'Insert/edit link',
  247. cmd: 'WP_Link',
  248. stateSelector: 'a[href]'
  249. });
  250. editor.addButton( 'unlink', {
  251. icon: 'unlink',
  252. tooltip: 'Remove link',
  253. cmd: 'unlink'
  254. });
  255. editor.addMenuItem( 'link', {
  256. icon: 'link',
  257. text: 'Insert/edit link',
  258. cmd: 'WP_Link',
  259. stateSelector: 'a[href]',
  260. context: 'insert',
  261. prependToContext: true
  262. });
  263. editor.on( 'pastepreprocess', function( event ) {
  264. var pastedStr = event.content,
  265. regExp = /^(?:https?:)?\/\/\S+$/i;
  266. if ( ! editor.selection.isCollapsed() && ! regExp.test( editor.selection.getContent() ) ) {
  267. pastedStr = pastedStr.replace( /<[^>]+>/g, '' );
  268. pastedStr = tinymce.trim( pastedStr );
  269. if ( regExp.test( pastedStr ) ) {
  270. editor.execCommand( 'mceInsertLink', false, {
  271. href: editor.dom.decode( pastedStr )
  272. } );
  273. event.preventDefault();
  274. }
  275. }
  276. } );
  277. // Remove any remaining placeholders on saving.
  278. editor.on( 'savecontent', function( event ) {
  279. event.content = removePlaceholderStrings( event.content, true );
  280. });
  281. // Prevent adding undo levels on inserting link placeholder.
  282. editor.on( 'BeforeAddUndo', function( event ) {
  283. if ( event.lastLevel && event.lastLevel.content && event.level.content &&
  284. event.lastLevel.content === removePlaceholderStrings( event.level.content ) ) {
  285. event.preventDefault();
  286. }
  287. });
  288. // When doing undo and redo with keyboard shortcuts (Ctrl|Cmd+Z, Ctrl|Cmd+Shift+Z, Ctrl|Cmd+Y),
  289. // set a flag to not focus the inline dialog. The editor has to remain focused so the users can do consecutive undo/redo.
  290. editor.on( 'keydown', function( event ) {
  291. if ( event.keyCode === 27 ) { // Esc
  292. editor.execCommand( 'wp_link_cancel' );
  293. }
  294. if ( event.altKey || ( tinymce.Env.mac && ( ! event.metaKey || event.ctrlKey ) ) ||
  295. ( ! tinymce.Env.mac && ! event.ctrlKey ) ) {
  296. return;
  297. }
  298. if ( event.keyCode === 89 || event.keyCode === 90 ) { // Y or Z
  299. doingUndoRedo = true;
  300. window.clearTimeout( doingUndoRedoTimer );
  301. doingUndoRedoTimer = window.setTimeout( function() {
  302. doingUndoRedo = false;
  303. }, 500 );
  304. }
  305. } );
  306. editor.addButton( 'wp_link_preview', {
  307. type: 'WPLinkPreview',
  308. onPostRender: function() {
  309. previewInstance = this;
  310. }
  311. } );
  312. editor.addButton( 'wp_link_input', {
  313. type: 'WPLinkInput',
  314. onPostRender: function() {
  315. var element = this.getEl(),
  316. input = element.firstChild,
  317. $input, cache, last;
  318. inputInstance = this;
  319. if ( $ && $.ui && $.ui.autocomplete ) {
  320. $input = $( input );
  321. $input.on( 'keydown', function() {
  322. $input.removeAttr( 'aria-activedescendant' );
  323. } )
  324. .autocomplete( {
  325. source: function( request, response ) {
  326. if ( last === request.term ) {
  327. response( cache );
  328. return;
  329. }
  330. if ( /^https?:/.test( request.term ) || request.term.indexOf( '.' ) !== -1 ) {
  331. return response();
  332. }
  333. $.post( window.ajaxurl, {
  334. action: 'wp-link-ajax',
  335. page: 1,
  336. search: request.term,
  337. _ajax_linking_nonce: $( '#_ajax_linking_nonce' ).val()
  338. }, function( data ) {
  339. cache = data;
  340. response( data );
  341. }, 'json' );
  342. last = request.term;
  343. },
  344. focus: function( event, ui ) {
  345. $input.attr( 'aria-activedescendant', 'mce-wp-autocomplete-' + ui.item.ID );
  346. /*
  347. * Don't empty the URL input field, when using the arrow keys to
  348. * highlight items. See api.jqueryui.com/autocomplete/#event-focus
  349. */
  350. event.preventDefault();
  351. },
  352. select: function( event, ui ) {
  353. $input.val( ui.item.permalink );
  354. $( element.firstChild.nextSibling ).val( ui.item.title );
  355. if ( 9 === event.keyCode && typeof window.wpLinkL10n !== 'undefined' ) {
  356. // Audible confirmation message when a link has been selected.
  357. speak( window.wpLinkL10n.linkSelected );
  358. }
  359. return false;
  360. },
  361. open: function() {
  362. $input.attr( 'aria-expanded', 'true' );
  363. editToolbar.blockHide = true;
  364. },
  365. close: function() {
  366. $input.attr( 'aria-expanded', 'false' );
  367. editToolbar.blockHide = false;
  368. },
  369. minLength: 2,
  370. position: {
  371. my: 'left top+2'
  372. },
  373. messages: {
  374. noResults: ( typeof window.uiAutocompleteL10n !== 'undefined' ) ? window.uiAutocompleteL10n.noResults : '',
  375. results: function( number ) {
  376. if ( typeof window.uiAutocompleteL10n !== 'undefined' ) {
  377. if ( number > 1 ) {
  378. return window.uiAutocompleteL10n.manyResults.replace( '%d', number );
  379. }
  380. return window.uiAutocompleteL10n.oneResult;
  381. }
  382. }
  383. }
  384. } ).autocomplete( 'instance' )._renderItem = function( ul, item ) {
  385. var fallbackTitle = ( typeof window.wpLinkL10n !== 'undefined' ) ? window.wpLinkL10n.noTitle : '',
  386. title = item.title ? item.title : fallbackTitle;
  387. return $( '<li role="option" id="mce-wp-autocomplete-' + item.ID + '">' )
  388. .append( '<span>' + title + '</span>&nbsp;<span class="wp-editor-float-right">' + item.info + '</span>' )
  389. .appendTo( ul );
  390. };
  391. $input.attr( {
  392. 'role': 'combobox',
  393. 'aria-autocomplete': 'list',
  394. 'aria-expanded': 'false',
  395. 'aria-owns': $input.autocomplete( 'widget' ).attr( 'id' )
  396. } )
  397. .on( 'focus', function() {
  398. var inputValue = $input.val();
  399. /*
  400. * Don't trigger a search if the URL field already has a link or is empty.
  401. * Also, avoids screen readers announce `No search results`.
  402. */
  403. if ( inputValue && ! /^https?:/.test( inputValue ) ) {
  404. $input.autocomplete( 'search' );
  405. }
  406. } )
  407. // Returns a jQuery object containing the menu element.
  408. .autocomplete( 'widget' )
  409. .addClass( 'wplink-autocomplete' )
  410. .attr( 'role', 'listbox' )
  411. .removeAttr( 'tabindex' ) // Remove the `tabindex=0` attribute added by jQuery UI.
  412. /*
  413. * Looks like Safari and VoiceOver need an `aria-selected` attribute. See ticket #33301.
  414. * The `menufocus` and `menublur` events are the same events used to add and remove
  415. * the `ui-state-focus` CSS class on the menu items. See jQuery UI Menu Widget.
  416. */
  417. .on( 'menufocus', function( event, ui ) {
  418. ui.item.attr( 'aria-selected', 'true' );
  419. })
  420. .on( 'menublur', function() {
  421. /*
  422. * The `menublur` event returns an object where the item is `null`
  423. * so we need to find the active item with other means.
  424. */
  425. $( this ).find( '[aria-selected="true"]' ).removeAttr( 'aria-selected' );
  426. });
  427. }
  428. tinymce.$( input ).on( 'keydown', function( event ) {
  429. if ( event.keyCode === 13 ) {
  430. editor.execCommand( 'wp_link_apply' );
  431. event.preventDefault();
  432. }
  433. } );
  434. }
  435. } );
  436. editor.on( 'wptoolbar', function( event ) {
  437. var linkNode = editor.dom.getParent( event.element, 'a' ),
  438. $linkNode, href, edit;
  439. if ( typeof window.wpLink !== 'undefined' && window.wpLink.modalOpen ) {
  440. editToolbar.tempHide = true;
  441. return;
  442. }
  443. editToolbar.tempHide = false;
  444. if ( linkNode ) {
  445. $linkNode = editor.$( linkNode );
  446. href = $linkNode.attr( 'href' );
  447. edit = $linkNode.attr( 'data-wplink-edit' );
  448. if ( href === '_wp_link_placeholder' || edit ) {
  449. if ( href !== '_wp_link_placeholder' && ! inputInstance.getURL() ) {
  450. inputInstance.setURL( href );
  451. }
  452. event.element = linkNode;
  453. event.toolbar = editToolbar;
  454. } else if ( href && ! $linkNode.find( 'img' ).length ) {
  455. previewInstance.setURL( href );
  456. event.element = linkNode;
  457. event.toolbar = toolbar;
  458. if ( $linkNode.attr( 'data-wplink-url-error' ) === 'true' ) {
  459. toolbar.$el.find( '.wp-link-preview a' ).addClass( 'wplink-url-error' );
  460. } else {
  461. toolbar.$el.find( '.wp-link-preview a' ).removeClass( 'wplink-url-error' );
  462. hasLinkError = false;
  463. }
  464. }
  465. } else if ( editToolbar.visible() ) {
  466. editor.execCommand( 'wp_link_cancel' );
  467. }
  468. } );
  469. editor.addButton( 'wp_link_edit', {
  470. tooltip: 'Edit|button', // '|button' is not displayed, only used for context
  471. icon: 'dashicon dashicons-edit',
  472. cmd: 'WP_Link'
  473. } );
  474. editor.addButton( 'wp_link_remove', {
  475. tooltip: 'Remove link',
  476. icon: 'dashicon dashicons-editor-unlink',
  477. cmd: 'wp_unlink'
  478. } );
  479. editor.addButton( 'wp_link_advanced', {
  480. tooltip: 'Link options',
  481. icon: 'dashicon dashicons-admin-generic',
  482. onclick: function() {
  483. if ( typeof window.wpLink !== 'undefined' ) {
  484. var url = inputInstance.getURL() || null,
  485. text = inputInstance.getLinkText() || null;
  486. window.wpLink.open( editor.id, url, text );
  487. editToolbar.tempHide = true;
  488. editToolbar.hide();
  489. }
  490. }
  491. } );
  492. editor.addButton( 'wp_link_apply', {
  493. tooltip: 'Apply',
  494. icon: 'dashicon dashicons-editor-break',
  495. cmd: 'wp_link_apply',
  496. classes: 'widget btn primary'
  497. } );
  498. return {
  499. close: function() {
  500. editToolbar.tempHide = false;
  501. editor.execCommand( 'wp_link_cancel' );
  502. },
  503. checkLink: checkLink
  504. };
  505. } );
  506. } )( window.tinymce );