8
0

link.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module link/link
  7. */
  8. import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
  9. import ClickObserver from '@ckeditor/ckeditor5-engine/src/view/observer/clickobserver';
  10. import Range from '@ckeditor/ckeditor5-engine/src/view/range';
  11. import LinkEngine from './linkengine';
  12. import LinkElement from './linkelement';
  13. import ContextualBalloon from '@ckeditor/ckeditor5-ui/src/panel/balloon/contextualballoon';
  14. import clickOutsideHandler from '@ckeditor/ckeditor5-ui/src/bindings/clickoutsidehandler';
  15. import ButtonView from '@ckeditor/ckeditor5-ui/src/button/buttonview';
  16. import LinkFormView from './ui/linkformview';
  17. import linkIcon from '../theme/icons/link.svg';
  18. const linkKeystroke = 'Ctrl+K';
  19. /**
  20. * The link plugin. It introduces the Link and Unlink buttons and the <kbd>Ctrl+K</kbd> keystroke.
  21. *
  22. * It uses the {@link module:link/linkengine~LinkEngine link engine plugin} and the
  23. * {@link module:ui/panel/balloon/contextualballoon~ContextualBalloon contextual balloon plugin}.
  24. *
  25. * @extends module:core/plugin~Plugin
  26. */
  27. export default class Link extends Plugin {
  28. /**
  29. * @inheritDoc
  30. */
  31. static get requires() {
  32. return [ LinkEngine, ContextualBalloon ];
  33. }
  34. /**
  35. * @inheritDoc
  36. */
  37. static get pluginName() {
  38. return 'Link';
  39. }
  40. /**
  41. * @inheritDoc
  42. */
  43. init() {
  44. const editor = this.editor;
  45. editor.editing.view.addObserver( ClickObserver );
  46. /**
  47. * The form view displayed inside the balloon.
  48. *
  49. * @member {module:link/ui/linkformview~LinkFormView}
  50. */
  51. this.formView = this._createForm();
  52. /**
  53. * The contextual balloon plugin instance.
  54. *
  55. * @private
  56. * @member {module:ui/panel/balloon/contextualballoon~ContextualBalloon}
  57. */
  58. this._balloon = editor.plugins.get( ContextualBalloon );
  59. // Create toolbar buttons.
  60. this._createToolbarLinkButton();
  61. // Attach lifecycle actions to the the balloon.
  62. this._attachActions();
  63. }
  64. /**
  65. * Creates the {@link module:link/ui/linkformview~LinkFormView} instance.
  66. *
  67. * @private
  68. * @returns {module:link/ui/linkformview~LinkFormView} The link form instance.
  69. */
  70. _createForm() {
  71. const editor = this.editor;
  72. const formView = new LinkFormView( editor.locale );
  73. const linkCommand = editor.commands.get( 'link' );
  74. const unlinkCommand = editor.commands.get( 'unlink' );
  75. formView.urlInputView.bind( 'value' ).to( linkCommand, 'value' );
  76. // Form elements should be read-only when corresponding commands are disabled.
  77. formView.urlInputView.bind( 'isReadOnly' ).to( linkCommand, 'isEnabled', value => !value );
  78. formView.saveButtonView.bind( 'isEnabled' ).to( linkCommand );
  79. formView.unlinkButtonView.bind( 'isEnabled' ).to( unlinkCommand );
  80. // Execute link command after clicking on formView `Save` button.
  81. this.listenTo( formView, 'submit', () => {
  82. editor.execute( 'link', formView.urlInputView.inputView.element.value );
  83. this._hidePanel( true );
  84. } );
  85. // Execute unlink command after clicking on formView `Unlink` button.
  86. this.listenTo( formView, 'unlink', () => {
  87. editor.execute( 'unlink' );
  88. this._hidePanel( true );
  89. } );
  90. // Hide the panel after clicking on formView `Cancel` button.
  91. this.listenTo( formView, 'cancel', () => this._hidePanel( true ) );
  92. // Close the panel on esc key press when the form has focus.
  93. formView.keystrokes.set( 'Esc', ( data, cancel ) => {
  94. this._hidePanel( true );
  95. cancel();
  96. } );
  97. return formView;
  98. }
  99. /**
  100. * Creates a toolbar Link button. Clicking this button will show
  101. * a {@link #_balloon} attached to the selection.
  102. *
  103. * @private
  104. */
  105. _createToolbarLinkButton() {
  106. const editor = this.editor;
  107. const linkCommand = editor.commands.get( 'link' );
  108. const t = editor.t;
  109. // Handle the `Ctrl+K` keystroke and show the panel.
  110. editor.keystrokes.set( linkKeystroke, ( keyEvtData, cancel ) => {
  111. // Prevent focusing the search bar in FF and opening new tab in Edge. #153, #154.
  112. cancel();
  113. if ( linkCommand.isEnabled ) {
  114. this._showPanel( true );
  115. }
  116. } );
  117. editor.ui.componentFactory.add( 'link', locale => {
  118. const button = new ButtonView( locale );
  119. button.isEnabled = true;
  120. button.label = t( 'Link' );
  121. button.icon = linkIcon;
  122. button.keystroke = linkKeystroke;
  123. button.tooltip = true;
  124. // Bind button to the command.
  125. button.bind( 'isEnabled' ).to( linkCommand, 'isEnabled' );
  126. // Show the panel on button click.
  127. this.listenTo( button, 'execute', () => this._showPanel( true ) );
  128. return button;
  129. } );
  130. }
  131. /**
  132. * Attaches actions that control whether the balloon panel containing the
  133. * {@link #formView} is visible or not.
  134. *
  135. * @private
  136. */
  137. _attachActions() {
  138. const viewDocument = this.editor.editing.view;
  139. // Handle click on view document and show panel when selection is placed inside the link element.
  140. // Keep panel open until selection will be inside the same link element.
  141. this.listenTo( viewDocument, 'click', () => {
  142. const parentLink = this._getSelectedLinkElement();
  143. if ( parentLink ) {
  144. // Then show panel but keep focus inside editor editable.
  145. this._showPanel();
  146. }
  147. } );
  148. // Focus the form if the balloon is visible and the Tab key has been pressed.
  149. this.editor.keystrokes.set( 'Tab', ( data, cancel ) => {
  150. if ( this._balloon.visibleView === this.formView && !this.formView.focusTracker.isFocused ) {
  151. this.formView.focus();
  152. cancel();
  153. }
  154. }, {
  155. // Use the high priority because the link UI navigation is more important
  156. // than other feature's actions, e.g. list indentation.
  157. // https://github.com/ckeditor/ckeditor5-link/issues/146
  158. priority: 'high'
  159. } );
  160. // Close the panel on the Esc key press when the editable has focus and the balloon is visible.
  161. this.editor.keystrokes.set( 'Esc', ( data, cancel ) => {
  162. if ( this._balloon.visibleView === this.formView ) {
  163. this._hidePanel();
  164. cancel();
  165. }
  166. } );
  167. // Close on click outside of balloon panel element.
  168. clickOutsideHandler( {
  169. emitter: this.formView,
  170. activator: () => this._balloon.hasView( this.formView ),
  171. contextElements: [ this._balloon.view.element ],
  172. callback: () => this._hidePanel()
  173. } );
  174. }
  175. /**
  176. * Adds the {@link #formView} to the {@link #_balloon}.
  177. *
  178. * @protected
  179. * @param {Boolean} [focusInput=false] When `true`, the link form will be focused on panel show.
  180. */
  181. _showPanel( focusInput ) {
  182. const editor = this.editor;
  183. const linkCommand = editor.commands.get( 'link' );
  184. const unlinkCommand = editor.commands.get( 'unlink' );
  185. const editing = editor.editing;
  186. const showViewDocument = editing.view;
  187. const showIsCollapsed = showViewDocument.selection.isCollapsed;
  188. const showSelectedLink = this._getSelectedLinkElement();
  189. this.listenTo( showViewDocument, 'render', () => {
  190. const renderSelectedLink = this._getSelectedLinkElement();
  191. const renderIsCollapsed = showViewDocument.selection.isCollapsed;
  192. const hasSellectionExpanded = showIsCollapsed && !renderIsCollapsed;
  193. // Hide the panel if:
  194. // * the selection went out of the original link element
  195. // (e.g. paragraph containing the link was removed),
  196. // * the selection has expanded
  197. // upon the #render event.
  198. if ( hasSellectionExpanded || showSelectedLink !== renderSelectedLink ) {
  199. this._hidePanel( true );
  200. }
  201. // Update the position of the panel when:
  202. // * the selection remains in the original link element,
  203. // * there was no link element in the first place, i.e. creating a new link
  204. else {
  205. // If still in a link element, simply update the position of the balloon.
  206. // If there was no link, upon #render, the balloon must be moved
  207. // to the new position in the editing view (a new native DOM range).
  208. this._balloon.updatePosition( this._getBalloonPositionData() );
  209. }
  210. } );
  211. if ( this._balloon.hasView( this.formView ) ) {
  212. // Check if formView should be focused and focus it if is visible.
  213. if ( focusInput && this._balloon.visibleView === this.formView ) {
  214. this.formView.urlInputView.select();
  215. }
  216. } else {
  217. this._balloon.add( {
  218. view: this.formView,
  219. position: this._getBalloonPositionData()
  220. } );
  221. if ( focusInput ) {
  222. this.formView.urlInputView.select();
  223. }
  224. }
  225. // https://github.com/ckeditor/ckeditor5-link/issues/53
  226. this.formView.unlinkButtonView.isVisible = unlinkCommand.isEnabled;
  227. // Make sure that each time the panel shows up, the URL field remains in sync with the value of
  228. // the command. If the user typed in the input, then canceled the balloon (`urlInputView#value` stays
  229. // unaltered) and re-opened it without changing the value of the link command (e.g. because they
  230. // clicked the same link), they would see the old value instead of the actual value of the command.
  231. // https://github.com/ckeditor/ckeditor5-link/issues/78
  232. // https://github.com/ckeditor/ckeditor5-link/issues/123
  233. this.formView.urlInputView.inputView.element.value = linkCommand.value || '';
  234. }
  235. /**
  236. * Removes the {@link #formView} from the {@link #_balloon}.
  237. *
  238. * See {@link #_showPanel}.
  239. *
  240. * @protected
  241. * @param {Boolean} [focusEditable=false] When `true`, editable focus will be restored on panel hide.
  242. */
  243. _hidePanel( focusEditable ) {
  244. this.stopListening( this.editor.editing.view, 'render' );
  245. if ( !this._balloon.hasView( this.formView ) ) {
  246. return;
  247. }
  248. if ( focusEditable ) {
  249. this.editor.editing.view.focus();
  250. }
  251. this.stopListening( this.editor.editing.view, 'render' );
  252. this._balloon.remove( this.formView );
  253. }
  254. /**
  255. * Returns positioning options for the {@link #_balloon}. They control the way the balloon is attached
  256. * to the target element or selection.
  257. *
  258. * If the selection is collapsed and inside a link element, the panel will be attached to the
  259. * entire link element. Otherwise, it will be attached to the selection.
  260. *
  261. * @private
  262. * @returns {module:utils/dom/position~Options}
  263. */
  264. _getBalloonPositionData() {
  265. const viewDocument = this.editor.editing.view;
  266. const targetLink = this._getSelectedLinkElement();
  267. const target = targetLink ?
  268. // When selection is inside link element, then attach panel to this element.
  269. viewDocument.domConverter.mapViewToDom( targetLink ) :
  270. // Otherwise attach panel to the selection.
  271. viewDocument.domConverter.viewRangeToDom( viewDocument.selection.getFirstRange() );
  272. return { target };
  273. }
  274. /**
  275. * Returns the {@link module:link/linkelement~LinkElement} under
  276. * the {@link module:engine/view/document~Document editing view's} selection or `null`
  277. * if there is none.
  278. *
  279. * **Note**: For a non–collapsed selection the `LinkElement` is only returned when **fully**
  280. * selected and the **only** element within the selection boundaries.
  281. *
  282. * @private
  283. * @returns {module:link/linkelement~LinkElement|null}
  284. */
  285. _getSelectedLinkElement() {
  286. const selection = this.editor.editing.view.selection;
  287. if ( selection.isCollapsed ) {
  288. return findLinkElementAncestor( selection.getFirstPosition() );
  289. } else {
  290. // The range for fully selected link is usually anchored in adjacent text nodes.
  291. // Trim it to get closer to the actual LinkElement.
  292. const range = selection.getFirstRange().getTrimmed();
  293. const startLink = findLinkElementAncestor( range.start );
  294. const endLink = findLinkElementAncestor( range.end );
  295. if ( !startLink || startLink != endLink ) {
  296. return null;
  297. }
  298. // Check if the LinkElement is fully selected.
  299. if ( Range.createIn( startLink ).getTrimmed().isEqual( range ) ) {
  300. return startLink;
  301. } else {
  302. return null;
  303. }
  304. }
  305. }
  306. }
  307. // Returns a `LinkElement` if there's one among the ancestors of the provided `Position`.
  308. //
  309. // @private
  310. // @param {module:engine/view/position~Position} View position to analyze.
  311. // @returns {module:link/linkelement~LinkElement|null} LinkElement at the position or null.
  312. function findLinkElementAncestor( position ) {
  313. return position.getAncestors().find( ancestor => ancestor instanceof LinkElement );
  314. }