You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

614 lines
17 KiB

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