UNPKG

2.81 kBJavaScriptView Raw
1/**
2 * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4 */
5/**
6 * @module link/unlinkcommand
7 */
8import { Command } from 'ckeditor5/src/core';
9import { findAttributeRange } from 'ckeditor5/src/typing';
10import { isLinkableElement } from './utils';
11/**
12 * The unlink command. It is used by the {@link module:link/link~Link link plugin}.
13 */
14export default class UnlinkCommand extends Command {
15 /**
16 * @inheritDoc
17 */
18 refresh() {
19 const model = this.editor.model;
20 const selection = model.document.selection;
21 const selectedElement = selection.getSelectedElement();
22 // A check for any integration that allows linking elements (e.g. `LinkImage`).
23 // Currently the selection reads attributes from text nodes only. See #7429 and #7465.
24 if (isLinkableElement(selectedElement, model.schema)) {
25 this.isEnabled = model.schema.checkAttribute(selectedElement, 'linkHref');
26 }
27 else {
28 this.isEnabled = model.schema.checkAttributeInSelection(selection, 'linkHref');
29 }
30 }
31 /**
32 * Executes the command.
33 *
34 * When the selection is collapsed, it removes the `linkHref` attribute from each node with the same `linkHref` attribute value.
35 * When the selection is non-collapsed, it removes the `linkHref` attribute from each node in selected ranges.
36 *
37 * # Decorators
38 *
39 * If {@link module:link/linkconfig~LinkConfig#decorators `config.link.decorators`} is specified,
40 * all configured decorators are removed together with the `linkHref` attribute.
41 *
42 * @fires execute
43 */
44 execute() {
45 const editor = this.editor;
46 const model = this.editor.model;
47 const selection = model.document.selection;
48 const linkCommand = editor.commands.get('link');
49 model.change(writer => {
50 // Get ranges to unlink.
51 const rangesToUnlink = selection.isCollapsed ?
52 [findAttributeRange(selection.getFirstPosition(), 'linkHref', selection.getAttribute('linkHref'), model)] :
53 model.schema.getValidRanges(selection.getRanges(), 'linkHref');
54 // Remove `linkHref` attribute from specified ranges.
55 for (const range of rangesToUnlink) {
56 writer.removeAttribute('linkHref', range);
57 // If there are registered custom attributes, then remove them during unlink.
58 if (linkCommand) {
59 for (const manualDecorator of linkCommand.manualDecorators) {
60 writer.removeAttribute(manualDecorator.id, range);
61 }
62 }
63 }
64 });
65 }
66}