link.js 12 KB

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