| 1 |
import { Plugin } from "@html_editor/plugin"; |
| 2 |
import { unwrapContents } from "@html_editor/utils/dom"; |
| 3 |
import { closestElement, descendants, selectElements } from "@html_editor/utils/dom_traversal"; |
| 4 |
import { findInSelection, callbacksForCursorUpdate } from "@html_editor/utils/selection"; |
| 5 |
import { _t } from "@web/core/l10n/translation"; |
| 6 |
import { LinkPopover } from "./link_popover"; |
| 7 |
import { DIRECTIONS, leftPos, nodeSize, rightPos } from "@html_editor/utils/position"; |
| 8 |
import { EMAIL_REGEX, URL_REGEX, cleanZWChars, deduceURLfromText } from "./utils"; |
| 9 |
import { |
| 10 |
isElement, |
| 11 |
isProtected, |
| 12 |
isProtecting, |
| 13 |
isVisible, |
| 14 |
isZwnbsp, |
| 15 |
} from "@html_editor/utils/dom_info"; |
| 16 |
import { KeepLast } from "@web/core/utils/concurrency"; |
| 17 |
import { rpc } from "@web/core/network/rpc"; |
| 18 |
import { memoize } from "@web/core/utils/functions"; |
| 19 |
import { withSequence } from "@html_editor/utils/resource"; |
| 20 |
import { isBlock, closestBlock } from "@html_editor/utils/blocks"; |
| 21 |
import { isHtmlContentSupported } from "@html_editor/core/selection_plugin"; |
| 22 |
import { isBrowserFirefox } from "@web/core/browser/feature_detection"; |
| 23 |
|
| 24 |
/** @typedef {import("@odoo/owl").Component} Component */ |
| 25 |
/** @typedef {import("plugins").CSSSelector} CSSSelector */ |
| 26 |
/** |
| 27 |
* @typedef {import("@html_editor/core/selection_plugin").EditorSelection} EditorSelection |
| 28 |
*/ |
| 29 |
|
| 30 |
/** |
| 31 |
* @param {EditorSelection} selection |
| 32 |
*/ |
| 33 |
function isLinkActive(selection) { |
| 34 |
const linkElementAnchor = closestElement(selection.anchorNode, "A"); |
| 35 |
const linkElementFocus = closestElement(selection.focusNode, "A"); |
| 36 |
if (linkElementFocus && linkElementAnchor) { |
| 37 |
return linkElementAnchor === linkElementFocus; |
| 38 |
} |
| 39 |
if (linkElementAnchor || linkElementFocus) { |
| 40 |
return true; |
| 41 |
} |
| 42 |
|
| 43 |
return false; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* @param { HTMLAnchorElement } link |
| 48 |
* @param {number} offset |
| 49 |
* @returns {"start"|"end"|false} |
| 50 |
*/ |
| 51 |
function isPositionAtEdgeofLink(link, offset) { |
| 52 |
const childNodes = [...link.childNodes]; |
| 53 |
if (!childNodes.length) { |
| 54 |
return "end"; |
| 55 |
} |
| 56 |
let firstVisibleIndex = childNodes.findIndex(isVisible); |
| 57 |
firstVisibleIndex = firstVisibleIndex === -1 ? 0 : firstVisibleIndex; |
| 58 |
if (offset <= firstVisibleIndex) { |
| 59 |
return "start"; |
| 60 |
} |
| 61 |
let lastVisibleIndex = childNodes.reverse().findIndex(isVisible); |
| 62 |
lastVisibleIndex = lastVisibleIndex === -1 ? 0 : childNodes.length - lastVisibleIndex; |
| 63 |
if (offset >= lastVisibleIndex) { |
| 64 |
return "end"; |
| 65 |
} |
| 66 |
return false; |
| 67 |
} |
| 68 |
|
| 69 |
async function fetchExternalMetaData(url) { |
| 70 |
// Get the external metadata |
| 71 |
try { |
| 72 |
return await rpc("/html_editor/link_preview_external", { |
| 73 |
preview_url: url, |
| 74 |
}); |
| 75 |
} catch { |
| 76 |
// when it's not possible to fetch the metadata we don't want to block the ui |
| 77 |
return; |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
async function fetchInternalMetaData(url) { |
| 82 |
// Get the internal metadata |
| 83 |
const keepLastPromise = new KeepLast(); |
| 84 |
const urlParsed = new URL(url); |
| 85 |
// Enforce the current page's protocol to prevent mixed content issues. |
| 86 |
if (urlParsed.protocol !== window.location.protocol) { |
| 87 |
urlParsed.protocol = window.location.protocol; |
| 88 |
} |
| 89 |
|
| 90 |
const result = await keepLastPromise |
| 91 |
.add(fetch(urlParsed)) |
| 92 |
.then((response) => response.text()) |
| 93 |
.then(async (content) => { |
| 94 |
const html_parser = new window.DOMParser(); |
| 95 |
const doc = html_parser.parseFromString(content, "text/html"); |
| 96 |
const internalUrlMetaData = await rpc("/html_editor/link_preview_internal", { |
| 97 |
preview_url: urlParsed.href, |
| 98 |
}); |
| 99 |
|
| 100 |
internalUrlMetaData["favicon"] = doc.querySelector("link[rel~='icon']"); |
| 101 |
internalUrlMetaData["ogTitle"] = doc.querySelector("[property='og:title']"); |
| 102 |
internalUrlMetaData["title"] = doc.querySelector("title"); |
| 103 |
|
| 104 |
return internalUrlMetaData; |
| 105 |
}) |
| 106 |
.catch((error) => { |
| 107 |
// HTTP error codes should not prevent to edit the links, so we |
| 108 |
// only check for proper instances of Error. |
| 109 |
if (error instanceof Error) { |
| 110 |
return Promise.reject(error); |
| 111 |
} |
| 112 |
}); |
| 113 |
return result; |
| 114 |
} |
| 115 |
|
| 116 |
async function fetchAttachmentMetaData(url, ormService) { |
| 117 |
try { |
| 118 |
const urlParsed = new URL(url, window.location.origin); |
| 119 |
const attachementId = parseInt(urlParsed.pathname.split("/").pop()); |
| 120 |
return ( |
| 121 |
await ormService.read("ir.attachment", [attachementId], ["name", "mimetype", "type"]) |
| 122 |
)[0]; |
| 123 |
} catch { |
| 124 |
return { name: url }; |
| 125 |
} |
| 126 |
} |
| 127 |
|
| 128 |
/** |
| 129 |
* @typedef { Object } LinkShared |
| 130 |
* @property { LinkPlugin['createLink'] } createLink |
| 131 |
* @property { LinkPlugin['getPathAsUrlCommand'] } getPathAsUrlCommand |
| 132 |
* @property { LinkPlugin['insertLink'] } insertLink |
| 133 |
*/ |
| 134 |
|
| 135 |
/** |
| 136 |
* @typedef {((link: HTMLLinkElement) => boolean)[]} is_link_editable_predicates |
| 137 |
* @typedef {((link: HTMLLinkElement) => boolean)[]} legit_empty_link_predicates |
| 138 |
* @typedef {(() => boolean)[]} link_compatible_selection_predicates |
| 139 |
* @typedef {CSSSelector[]} immutable_link_selectors |
| 140 |
* @typedef {{ |
| 141 |
* PopoverClass: Component; |
| 142 |
* isAvailable: (linkEl: HTMLLinkElement) => boolean; |
| 143 |
* getProps: (props) => props; |
| 144 |
* }[]} link_popovers |
| 145 |
* @typedef {((linkEl: HTMLAnchorElement) => void)[]} create_link_handlers |
| 146 |
*/ |
| 147 |
|
| 148 |
export class LinkPlugin extends Plugin { |
| 149 |
static id = "link"; |
| 150 |
static dependencies = [ |
| 151 |
"dom", |
| 152 |
"history", |
| 153 |
"input", |
| 154 |
"selection", |
| 155 |
"split", |
| 156 |
"lineBreak", |
| 157 |
"overlay", |
| 158 |
"color", |
| 159 |
"baseContainer", |
| 160 |
"feff", |
| 161 |
]; |
| 162 |
static defaultConfig = { |
| 163 |
allowStripDomain: true, |
| 164 |
}; |
| 165 |
// @phoenix @todo: do we want to have createLink and insertLink methods in link plugin? |
| 166 |
static shared = ["createLink", "insertLink", "getPathAsUrlCommand"]; |
| 167 |
/** @type {import("plugins").EditorResources} */ |
| 168 |
resources = { |
| 169 |
user_commands: [ |
| 170 |
{ |
| 171 |
id: "openLinkTools", |
| 172 |
title: _t("Link"), |
| 173 |
description: _t("Add a link"), |
| 174 |
icon: "fa-link", |
| 175 |
run: ({ link, type } = {}) => this.openLinkTools(link, type), |
| 176 |
isAvailable: (selection) => { |
| 177 |
const linkEl = findInSelection(selection, "a"); |
| 178 |
return linkEl |
| 179 |
? this.getResource("link_popovers").some((p) => p.isAvailable(linkEl)) |
| 180 |
: isHtmlContentSupported(selection); |
| 181 |
}, |
| 182 |
}, |
| 183 |
{ |
| 184 |
id: "removeLinkFromSelection", |
| 185 |
title: _t("Remove Link"), |
| 186 |
description: _t("Remove Link"), |
| 187 |
icon: "fa-unlink", |
| 188 |
isAvailable: (selection) => { |
| 189 |
if (!isHtmlContentSupported(selection)) { |
| 190 |
return false; |
| 191 |
} |
| 192 |
for (const node of this.dependencies.selection.getTargetedNodes()) { |
| 193 |
const linkEl = closestElement(node, "a"); |
| 194 |
if ( |
| 195 |
linkEl && |
| 196 |
!this.isLinkImmutable(linkEl) && |
| 197 |
linkEl.parentElement.isContentEditable |
| 198 |
) { |
| 199 |
return true; |
| 200 |
} |
| 201 |
} |
| 202 |
}, |
| 203 |
run: this.removeLinkFromSelection.bind(this), |
| 204 |
}, |
| 205 |
], |
| 206 |
|
| 207 |
toolbar_groups: [ |
| 208 |
withSequence(40, { id: "link", namespaces: ["compact", "expanded"] }), |
| 209 |
withSequence(30, { id: "image_link", namespaces: ["image"] }), |
| 210 |
], |
| 211 |
toolbar_items: [ |
| 212 |
{ |
| 213 |
id: "link", |
| 214 |
groupId: "link", |
| 215 |
commandId: "openLinkTools", |
| 216 |
isActive: isLinkActive, |
| 217 |
isDisabled: () => !this.isLinkAllowedOnSelection(), |
| 218 |
}, |
| 219 |
{ |
| 220 |
id: "unlink", |
| 221 |
groupId: "link", |
| 222 |
commandId: "removeLinkFromSelection", |
| 223 |
isDisabled: () => this.removeLinkFromSelectionIsDisabled(), |
| 224 |
}, |
| 225 |
{ |
| 226 |
id: "link", |
| 227 |
groupId: "image_link", |
| 228 |
commandId: "openLinkTools", |
| 229 |
isActive: isLinkActive, |
| 230 |
isDisabled: () => !this.isLinkAllowedOnSelection(), |
| 231 |
}, |
| 232 |
{ |
| 233 |
id: "unlink", |
| 234 |
groupId: "image_link", |
| 235 |
commandId: "removeLinkFromSelection", |
| 236 |
isDisabled: () => this.removeLinkFromSelectionIsDisabled(), |
| 237 |
}, |
| 238 |
], |
| 239 |
|
| 240 |
powerbox_categories: withSequence(50, { id: "navigation", name: _t("Navigation") }), |
| 241 |
powerbox_items: [ |
| 242 |
{ |
| 243 |
categoryId: "navigation", |
| 244 |
commandId: "openLinkTools", |
| 245 |
}, |
| 246 |
{ |
| 247 |
title: _t("Button"), |
| 248 |
description: _t("Add a button"), |
| 249 |
categoryId: "navigation", |
| 250 |
commandId: "openLinkTools", |
| 251 |
commandParams: { type: "primary" }, |
| 252 |
}, |
| 253 |
], |
| 254 |
|
| 255 |
power_buttons: withSequence(10, { |
| 256 |
commandId: "openLinkTools", |
| 257 |
commandParams: { type: "primary" }, |
| 258 |
description: _t("Add a button"), |
| 259 |
icon: "fa-square", |
| 260 |
}), |
| 261 |
|
| 262 |
link_popovers: [ |
| 263 |
withSequence(50, { |
| 264 |
//Default option |
| 265 |
PopoverClass: LinkPopover, |
| 266 |
isAvailable: (linkEl) => !linkEl || !this.isLinkImmutable(linkEl), |
| 267 |
getProps: (props) => props, |
| 268 |
}), |
| 269 |
], |
| 270 |
|
| 271 |
immutable_link_selectors: [ |
| 272 |
'[data-bs-toggle="tab"]', |
| 273 |
'[data-bs-toggle="collapse"]', |
| 274 |
'[data-bs-toggle="dropdown"]', |
| 275 |
".dropdown-item", |
| 276 |
"[data-oe-model]", |
| 277 |
":has(>[data-oe-model])", |
| 278 |
".o_prevent_link_editor a", |
| 279 |
], |
| 280 |
legit_empty_link_predicates: (linkEl) => linkEl.hasAttribute("data-mimetype"), |
| 281 |
|
| 282 |
/** Handlers */ |
| 283 |
beforeinput_handlers: withSequence(5, this.onBeforeInput.bind(this)), |
| 284 |
input_handlers: this.onInputDeleteNormalizeLink.bind(this), |
| 285 |
before_delete_handlers: this.updateCurrentLinkSyncState.bind(this), |
| 286 |
delete_handlers: this.onInputDeleteNormalizeLink.bind(this), |
| 287 |
before_paste_handlers: this.updateCurrentLinkSyncState.bind(this), |
| 288 |
after_paste_handlers: this.onPasteNormalizeLink.bind(this), |
| 289 |
selectionchange_handlers: this.handleSelectionChange.bind(this), |
| 290 |
clean_for_save_handlers: ({ root }) => this.removeEmptyLinks(root), |
| 291 |
normalize_handlers: this.normalizeLink.bind(this), |
| 292 |
after_insert_handlers: this.handleAfterInsert.bind(this), |
| 293 |
on_will_remove_handlers: () => this.closeLinkTools(), |
| 294 |
|
| 295 |
/** Overrides */ |
| 296 |
split_element_block_overrides: this.handleSplitBlock.bind(this), |
| 297 |
insert_line_break_element_overrides: this.handleInsertLineBreak.bind(this), |
| 298 |
delete_image_overrides: this.deleteImageLink.bind(this), |
| 299 |
double_click_overrides: this.doubleClickLinkOverrides.bind(this), |
| 300 |
triple_click_overrides: this.tripleClickButtonOverrides.bind(this), |
| 301 |
|
| 302 |
/** Processors */ |
| 303 |
to_inline_code_processors: (node) => { |
| 304 |
this.removeEmptyLinks(node); |
| 305 |
for (const btn of selectElements(node, "a.btn")) { |
| 306 |
// Remove all attributes from the button link except "href" |
| 307 |
[...btn.attributes].forEach( |
| 308 |
(attr) => attr.name !== "href" && btn.removeAttribute(attr.name) |
| 309 |
); |
| 310 |
} |
| 311 |
}, |
| 312 |
}; |
| 313 |
|
| 314 |
setup() { |
| 315 |
this.initializePopovers(); |
| 316 |
this.currentOverlay = this.getActivePopover().overlay; |
| 317 |
this.addDomListener(this.editable, "click", (ev) => { |
| 318 |
const linkEl = ev.target.closest("a"); |
| 319 |
if (linkEl) { |
| 320 |
if (ev.ctrlKey || ev.metaKey) { |
| 321 |
window.open(linkEl.href, "_blank"); |
| 322 |
} |
| 323 |
ev.preventDefault(); |
| 324 |
} |
| 325 |
}); |
| 326 |
this.addDomListener(this.editable, "mousedown", () => { |
| 327 |
this._isNavigatingByMouse = true; |
| 328 |
}); |
| 329 |
this.addDomListener(this.editable, "keydown", () => { |
| 330 |
delete this._isNavigatingByMouse; |
| 331 |
}); |
| 332 |
this.addDomListener(this.editable, "auxclick", (ev) => { |
| 333 |
if (ev.button === 1) { |
| 334 |
const link = closestElement(ev.target, "a"); |
| 335 |
if (link?.href) { |
| 336 |
window.open(link.href, "_blank"); |
| 337 |
ev.preventDefault(); |
| 338 |
} |
| 339 |
} |
| 340 |
}); |
| 341 |
// link creation is added to the command service because of a shortcut conflict, |
| 342 |
// as ctrl+k is used for invoking the command palette |
| 343 |
this.unregisterLinkCommandCallback = this.services.command?.add( |
| 344 |
"Create link", |
| 345 |
() => { |
| 346 |
this.dependencies.selection.focusEditable(); |
| 347 |
// To avoid a race condition between the events spawn by : |
| 348 |
// 1. the `focus editable` and |
| 349 |
// 2. the odoo `Shortcut bar` closure |
| 350 |
// Which can affect the link overlay opening sequence if we keep it in sync. |
| 351 |
// Therefore we need to wait for the next tick before triggering openLinkTools. |
| 352 |
setTimeout(() => this.openLinkTools()); |
| 353 |
}, |
| 354 |
{ |
| 355 |
hotkey: "control+k", |
| 356 |
category: "shortcut_conflict", |
| 357 |
isAvailable: () => { |
| 358 |
const selectionData = this.dependencies.selection.getSelectionData(); |
| 359 |
return ( |
| 360 |
selectionData.documentSelectionIsInEditable && |
| 361 |
isHtmlContentSupported(selectionData.editableSelection) |
| 362 |
); |
| 363 |
}, |
| 364 |
} |
| 365 |
); |
| 366 |
|
| 367 |
this.getExternalMetaData = memoize(fetchExternalMetaData); |
| 368 |
this.getInternalMetaData = memoize(fetchInternalMetaData); |
| 369 |
this.getAttachmentMetadata = memoize((url) => |
| 370 |
fetchAttachmentMetaData(url, this.services.orm) |
| 371 |
); |
| 372 |
this.LinkPopoverState = { editing: false }; |
| 373 |
this.newlyInsertedLinks = new Set(); |
| 374 |
} |
| 375 |
|
| 376 |
destroy() { |
| 377 |
this.unregisterLinkCommandCallback?.(); |
| 378 |
} |
| 379 |
|
| 380 |
// ------------------------------------------------------------------------- |
| 381 |
// Commands |
| 382 |
// ------------------------------------------------------------------------- |
| 383 |
|
| 384 |
/** |
| 385 |
* @param {string} url |
| 386 |
* @param {string} label |
| 387 |
* |
| 388 |
* @return {HTMLElement} link |
| 389 |
*/ |
| 390 |
createLink(url, label = "") { |
| 391 |
const link = this.document.createElement("a"); |
| 392 |
if (url !== undefined) { |
| 393 |
link.setAttribute("href", url); |
| 394 |
} |
| 395 |
for (const [param, value] of Object.entries(this.config.defaultLinkAttributes || {})) { |
| 396 |
link.setAttribute(param, `${value}`); |
| 397 |
} |
| 398 |
link.innerText = label; |
| 399 |
this.dispatchTo("create_link_handlers", link); |
| 400 |
return link; |
| 401 |
} |
| 402 |
|
| 403 |
/** |
| 404 |
* @param {string} url |
| 405 |
* @param {string} label |
| 406 |
*/ |
| 407 |
insertLink(url, label) { |
| 408 |
const selection = this.dependencies.selection.getEditableSelection(); |
| 409 |
let link = closestElement(selection.anchorNode, "a"); |
| 410 |
if (link) { |
| 411 |
link.setAttribute("href", url); |
| 412 |
link.innerText = label; |
| 413 |
} else { |
| 414 |
link = this.createLink(url, label); |
| 415 |
this.dependencies.dom.insert(link); |
| 416 |
} |
| 417 |
this.dependencies.history.addStep(); |
| 418 |
const linkParent = link.parentElement; |
| 419 |
const linkOffset = Array.from(linkParent.childNodes).indexOf(link); |
| 420 |
this.dependencies.selection.setSelection( |
| 421 |
{ anchorNode: linkParent, anchorOffset: linkOffset + 1 }, |
| 422 |
{ normalize: false } |
| 423 |
); |
| 424 |
} |
| 425 |
|
| 426 |
/** |
| 427 |
* @param {string} text |
| 428 |
* @param {string} url |
| 429 |
*/ |
| 430 |
getPathAsUrlCommand(text, url) { |
| 431 |
const pasteAsURLCommand = { |
| 432 |
title: _t("Paste as URL"), |
| 433 |
description: _t("Create an URL."), |
| 434 |
icon: "fa-link", |
| 435 |
run: () => { |
| 436 |
this.dispatchTo( |
| 437 |
"before_paste_handlers", |
| 438 |
this.dependencies.selection.getEditableSelection() |
| 439 |
); |
| 440 |
this.dependencies.dom.insert(this.createLink(url, text)); |
| 441 |
this.dependencies.history.addStep(); |
| 442 |
}, |
| 443 |
}; |
| 444 |
return pasteAsURLCommand; |
| 445 |
} |
| 446 |
|
| 447 |
isLinkAllowedOnSelection() { |
| 448 |
if (this.getResource("link_compatible_selection_predicates").some((p) => p())) { |
| 449 |
return true; |
| 450 |
} |
| 451 |
const targetedNodes = this.dependencies.selection.getTargetedNodes(); |
| 452 |
const targetedBlocks = targetedNodes.filter(isBlock); |
| 453 |
const linksInSelection = targetedNodes.filter((n) => n.tagName === "A"); |
| 454 |
return ( |
| 455 |
linksInSelection.length < 2 && |
| 456 |
// Prevent a link across sibling blocks: |
| 457 |
targetedBlocks.every((node) => |
| 458 |
targetedNodes.every((other) => node.contains(other) || other.contains(node)) |
| 459 |
) |
| 460 |
); |
| 461 |
} |
| 462 |
|
| 463 |
/** |
| 464 |
* open the Link popover to edit links |
| 465 |
* |
| 466 |
* @param {HTMLElement} [linkElement] |
| 467 |
*/ |
| 468 |
openLinkTools(linkElement, type) { |
| 469 |
this.currentOverlay.close(); |
| 470 |
this.LinkPopoverState.editing = false; |
| 471 |
if (!this.isLinkAllowedOnSelection()) { |
| 472 |
return this.services.notification.add( |
| 473 |
_t("Unable to create a link on the current selection."), |
| 474 |
{ type: "danger" } |
| 475 |
); |
| 476 |
} |
| 477 |
let selection = this.dependencies.selection.getEditableSelection(); |
| 478 |
let cursorsToRestore = this.dependencies.selection.preserveSelection(); |
| 479 |
const commonAncestor = closestElement(selection.commonAncestorContainer); |
| 480 |
linkElement = linkElement || findInSelection(selection, "a"); |
| 481 |
this.type = type; |
| 482 |
if ( |
| 483 |
linkElement && |
| 484 |
(!linkElement.contains(selection.anchorNode) || |
| 485 |
!linkElement.contains(selection.focusNode)) |
| 486 |
) { |
| 487 |
this.extendLinkToSelection(linkElement, selection); |
| 488 |
linkElement = findInSelection(selection, "a"); |
| 489 |
this.dependencies.history.addStep(); |
| 490 |
cursorsToRestore = this.dependencies.selection.preserveSelection(); |
| 491 |
} |
| 492 |
this.linkInDocument = linkElement; |
| 493 |
if (!linkElement) { |
| 494 |
// create a new link element |
| 495 |
linkElement = this.createLink(undefined, selection.textContent()); |
| 496 |
} |
| 497 |
|
| 498 |
const selectionTextContent = selection?.textContent(); |
| 499 |
const isImage = !!findInSelection(selection, "img"); |
| 500 |
|
| 501 |
const applyCallback = ( |
| 502 |
url, |
| 503 |
label, |
| 504 |
classes, |
| 505 |
customStyle, |
| 506 |
linkTarget, |
| 507 |
attachmentId, |
| 508 |
relValue |
| 509 |
) => { |
| 510 |
if (this.linkInDocument) { |
| 511 |
if (url) { |
| 512 |
this.linkInDocument.href = url; |
| 513 |
} else { |
| 514 |
this.linkInDocument.removeAttribute("href"); |
| 515 |
} |
| 516 |
if (relValue) { |
| 517 |
this.linkInDocument.setAttribute("rel", relValue); |
| 518 |
} else { |
| 519 |
this.linkInDocument.removeAttribute("rel"); |
| 520 |
} |
| 521 |
if (linkTarget) { |
| 522 |
this.linkInDocument.setAttribute("target", linkTarget); |
| 523 |
} else { |
| 524 |
this.linkInDocument.removeAttribute("target"); |
| 525 |
} |
| 526 |
if (!isImage) { |
| 527 |
if (classes) { |
| 528 |
this.linkInDocument.className = classes; |
| 529 |
} else { |
| 530 |
this.linkInDocument.removeAttribute("class"); |
| 531 |
} |
| 532 |
if (customStyle) { |
| 533 |
this.linkInDocument.setAttribute("style", customStyle); |
| 534 |
} else { |
| 535 |
this.linkInDocument.removeAttribute("style"); |
| 536 |
} |
| 537 |
if ( |
| 538 |
this.linkInDocument.childElementCount == 0 && |
| 539 |
cleanZWChars(this.linkInDocument.innerText) !== label |
| 540 |
) { |
| 541 |
this.linkInDocument.innerText = label; |
| 542 |
cursorsToRestore = null; |
| 543 |
} |
| 544 |
} |
| 545 |
} else if (url) { |
| 546 |
// prevent the link creation if the url field was empty |
| 547 |
|
| 548 |
// create a new link with current selection as a content |
| 549 |
if ((selectionTextContent && selectionTextContent === label) || isImage) { |
| 550 |
const link = this.createLink(url); |
| 551 |
if (relValue) { |
| 552 |
link.setAttribute("rel", relValue); |
| 553 |
} |
| 554 |
const image = isImage && findInSelection(selection, "img"); |
| 555 |
const figure = |
| 556 |
image?.parentElement?.matches("figure[contenteditable=false]") && |
| 557 |
image.parentElement; |
| 558 |
if (figure) { |
| 559 |
figure.before(link); |
| 560 |
link.append(figure); |
| 561 |
if (link.parentElement === this.editable) { |
| 562 |
const baseContainer = |
| 563 |
this.dependencies.baseContainer.createBaseContainer(); |
| 564 |
link.before(baseContainer); |
| 565 |
baseContainer.append(link); |
| 566 |
} |
| 567 |
} else { |
| 568 |
const content = this.dependencies.selection.extractContent(selection); |
| 569 |
link.append(content); |
| 570 |
link.normalize(); |
| 571 |
cursorsToRestore = null; |
| 572 |
selection = this.dependencies.selection.getEditableSelection(); |
| 573 |
const anchorClosestElement = closestElement(selection.anchorNode); |
| 574 |
if (commonAncestor !== anchorClosestElement) { |
| 575 |
// We force the cursor after the anchorClosestElement |
| 576 |
// To be sure the link is inserted in the correct place in the dom. |
| 577 |
const [anchorNode, anchorOffset] = rightPos(anchorClosestElement); |
| 578 |
this.dependencies.selection.setSelection( |
| 579 |
{ anchorNode, anchorOffset }, |
| 580 |
{ normalize: false } |
| 581 |
); |
| 582 |
} |
| 583 |
this.dependencies.dom.insert(link); |
| 584 |
} |
| 585 |
this.linkInDocument = link; |
| 586 |
} else if (label) { |
| 587 |
const link = this.createLink(url, label); |
| 588 |
if (classes) { |
| 589 |
link.className = classes; |
| 590 |
} |
| 591 |
if (customStyle) { |
| 592 |
link.setAttribute("style", customStyle); |
| 593 |
} |
| 594 |
if (linkTarget) { |
| 595 |
link.setAttribute("target", linkTarget); |
| 596 |
} |
| 597 |
this.linkInDocument = link; |
| 598 |
cursorsToRestore = null; |
| 599 |
this.dependencies.dom.insert(link); |
| 600 |
} |
| 601 |
} |
| 602 |
if (attachmentId) { |
| 603 |
this.linkInDocument.dataset.attachmentId = attachmentId; |
| 604 |
} |
| 605 |
}; |
| 606 |
|
| 607 |
this.restoreSavePoint = this.dependencies.history.makeSavePoint(); |
| 608 |
const props = { |
| 609 |
document: this.document, |
| 610 |
linkElement, |
| 611 |
isImage: isImage, |
| 612 |
onApply: (...args) => { |
| 613 |
delete this._isNavigatingByMouse; |
| 614 |
applyCallback(...args); |
| 615 |
this.closeLinkTools(cursorsToRestore); |
| 616 |
this.dependencies.selection.focusEditable(); |
| 617 |
this.dependencies.history.addStep(); |
| 618 |
}, |
| 619 |
onChange: applyCallback, |
| 620 |
onDiscard: () => { |
| 621 |
this.restoreSavePoint(); |
| 622 |
if (linkElement.isConnected) { |
| 623 |
this.openLinkTools(linkElement); |
| 624 |
} else { |
| 625 |
this.linkInDocument = null; |
| 626 |
this.currentOverlay.close(); |
| 627 |
} |
| 628 |
this.dependencies.selection.focusEditable(); |
| 629 |
}, |
| 630 |
onRemove: () => { |
| 631 |
this.removeLinkInDocument(); |
| 632 |
this.linkInDocument = null; |
| 633 |
this.currentOverlay.close(); |
| 634 |
}, |
| 635 |
onCopy: () => { |
| 636 |
this.linkInDocument = null; |
| 637 |
this.currentOverlay.close(); |
| 638 |
}, |
| 639 |
onEdit: () => { |
| 640 |
this.restoreSavePoint = this.dependencies.history.makeSavePoint(); |
| 641 |
}, |
| 642 |
getInternalMetaData: this.getInternalMetaData, |
| 643 |
getExternalMetaData: this.getExternalMetaData, |
| 644 |
getAttachmentMetadata: this.getAttachmentMetadata, |
| 645 |
recordInfo: this.config.getRecordInfo?.() || {}, |
| 646 |
canEdit: |
| 647 |
!this.linkInDocument || !this.linkInDocument.classList.contains("o_link_readonly"), |
| 648 |
canRemove: |
| 649 |
this.linkInDocument && |
| 650 |
this.linkInDocument.parentElement.isContentEditable && |
| 651 |
!this.isUnremovable(this.linkInDocument), |
| 652 |
canUpload: this.config.allowFile, |
| 653 |
onUpload: this.config.onAttachmentChange, |
| 654 |
type: this.type || "", |
| 655 |
LinkPopoverState: this.LinkPopoverState, |
| 656 |
showReplaceTitleBanner: this.newlyInsertedLinks.has(linkElement), |
| 657 |
allowCustomStyle: this.config.allowCustomStyle, |
| 658 |
allowTargetBlank: this.config.allowTargetBlank, |
| 659 |
allowStripDomain: this.config.allowStripDomain, |
| 660 |
}; |
| 661 |
|
| 662 |
const popover = this.getActivePopover(linkElement); |
| 663 |
if (popover) { |
| 664 |
this.currentOverlay = popover.overlay; |
| 665 |
if (!linkElement.href) { |
| 666 |
this.LinkPopoverState.editing = true; |
| 667 |
} |
| 668 |
this.currentOverlay.open({ props: popover.getProps(props) }); |
| 669 |
if (this.linkInDocument) { |
| 670 |
if (this.newlyInsertedLinks.has(this.linkInDocument)) { |
| 671 |
this.newlyInsertedLinks.delete(this.linkInDocument); |
| 672 |
} |
| 673 |
} |
| 674 |
} |
| 675 |
} |
| 676 |
|
| 677 |
/** |
| 678 |
* close the link tool |
| 679 |
* |
| 680 |
*/ |
| 681 |
closeLinkTools(cursors = null) { |
| 682 |
const link = this.linkInDocument; |
| 683 |
this.linkInDocument = null; |
| 684 |
// Some unit tests fail when this.overlay.isOpen but the DOM don't contain the linkPopover yet. |
| 685 |
// Because of some kind of race condition between the hoot mock event and the owl renderer. |
| 686 |
// This is why we check for the popover in the DOM. |
| 687 |
if (this.currentOverlay.isOpen && document.querySelector(".o-we-linkpopover")) { |
| 688 |
this.currentOverlay.close(); |
| 689 |
if (link && link.isConnected) { |
| 690 |
this.dependencies.selection.setSelection({ |
| 691 |
anchorNode: link, |
| 692 |
anchorOffset: 0, |
| 693 |
focusNode: link, |
| 694 |
focusOffset: nodeSize(link), |
| 695 |
}); |
| 696 |
const saveCustomStyle = link.getAttribute("style"); |
| 697 |
link.removeAttribute("style"); |
| 698 |
this.dependencies.color.removeAllColor(); |
| 699 |
if ( |
| 700 |
saveCustomStyle && |
| 701 |
this.config.allowCustomStyle && |
| 702 |
link.className.includes("custom") |
| 703 |
) { |
| 704 |
link.setAttribute("style", saveCustomStyle); |
| 705 |
} |
| 706 |
// Remove the current link (linkInDocument) if it has no content |
| 707 |
if (cleanZWChars(link.textContent) === "" && !link.querySelector("img")) { |
| 708 |
const [anchorNode, anchorOffset] = rightPos(link); |
| 709 |
// We force the cursor after the link before removing the link |
| 710 |
// to ensure we don't lose the selection position. |
| 711 |
this.dependencies.selection.setSelection( |
| 712 |
{ anchorNode, anchorOffset }, |
| 713 |
{ normalize: false } |
| 714 |
); |
| 715 |
link.remove(); |
| 716 |
} else if (cursors) { |
| 717 |
cursors.restore(); |
| 718 |
} else { |
| 719 |
this.dependencies.selection.setCursorEnd(link); |
| 720 |
} |
| 721 |
} |
| 722 |
} |
| 723 |
} |
| 724 |
|
| 725 |
normalizeLink(root) { |
| 726 |
for (const anchorEl of selectElements(root, "a")) { |
| 727 |
if (/btn(-[a-z0-9_-]*)custom/.test(anchorEl.className)) { |
| 728 |
// if the link is a customized button, we don't want to change the color |
| 729 |
continue; |
| 730 |
} |
| 731 |
const { color } = anchorEl.style; |
| 732 |
const childNodes = [...anchorEl.childNodes]; |
| 733 |
// For each anchor element, if it has an inline color style, |
| 734 |
// (converted from an external style), remove it from the anchor, |
| 735 |
// create a font tag inside it, and move the color to the font tag. |
| 736 |
// This ensures the color is applied to the font element instead of |
| 737 |
// the anchor element itself. |
| 738 |
if (color && childNodes.every((n) => !isBlock(n))) { |
| 739 |
anchorEl.style.removeProperty("color"); |
| 740 |
const font = selectElements(anchorEl, "font").next().value; |
| 741 |
if (font && cleanZWChars(anchorEl.textContent) === font.textContent) { |
| 742 |
continue; |
| 743 |
} |
| 744 |
const newFont = this.document.createElement("font"); |
| 745 |
newFont.append(...childNodes); |
| 746 |
anchorEl.appendChild(newFont); |
| 747 |
this.dependencies.color.colorElement(newFont, color, "color"); |
| 748 |
} |
| 749 |
|
| 750 |
// When a link contains unsupported element (like an iframe or a link), |
| 751 |
// we remove the link. Cases can happen when a image link is replaced |
| 752 |
// by a document or a video |
| 753 |
const hasUnsupportedMedia = anchorEl.querySelector("a, iframe"); |
| 754 |
if (hasUnsupportedMedia) { |
| 755 |
this.removeLinkInDocument(anchorEl); |
| 756 |
} |
| 757 |
} |
| 758 |
} |
| 759 |
|
| 760 |
handleSelectionChange(selectionData) { |
| 761 |
const selection = selectionData.editableSelection; |
| 762 |
if ( |
| 763 |
this._isNavigatingByMouse && |
| 764 |
selection.isCollapsed && |
| 765 |
selectionData.documentSelectionIsInEditable |
| 766 |
) { |
| 767 |
delete this._isNavigatingByMouse; |
| 768 |
const { startContainer, startOffset, endContainer, endOffset } = selection; |
| 769 |
const linkElement = closestElement(startContainer, "a"); |
| 770 |
if ( |
| 771 |
linkElement && |
| 772 |
linkElement.textContent.startsWith("\uFEFF") && |
| 773 |
linkElement.textContent.endsWith("\uFEFF") |
| 774 |
) { |
| 775 |
const linkDescendants = descendants(linkElement); |
| 776 |
|
| 777 |
// Check if the cursor is positioned at the begining of link. |
| 778 |
const isCursorAtStartOfLink = isZwnbsp(startContainer) |
| 779 |
? linkDescendants.indexOf(startContainer) === 0 |
| 780 |
: startContainer.nodeType === Node.TEXT_NODE && |
| 781 |
linkDescendants.indexOf(startContainer) === 1 && |
| 782 |
startOffset === 0; |
| 783 |
|
| 784 |
// Check if the cursor is positioned at the end of link. |
| 785 |
const isCursorAtEndOfLink = isZwnbsp(endContainer) |
| 786 |
? linkDescendants.indexOf(endContainer) === linkDescendants.length - 1 |
| 787 |
: endContainer.nodeType === Node.TEXT_NODE && |
| 788 |
linkDescendants.indexOf(endContainer) === linkDescendants.length - 2 && |
| 789 |
endOffset === nodeSize(endContainer); |
| 790 |
|
| 791 |
// Handle selection movement. |
| 792 |
if (isCursorAtStartOfLink || isCursorAtEndOfLink) { |
| 793 |
const [targetNode, targetOffset] = isCursorAtStartOfLink |
| 794 |
? leftPos(linkElement) |
| 795 |
: rightPos(linkElement); |
| 796 |
this.dependencies.selection.setSelection({ |
| 797 |
anchorNode: targetNode, |
| 798 |
anchorOffset: isCursorAtStartOfLink ? targetOffset - 1 : targetOffset + 1, |
| 799 |
}); |
| 800 |
return; |
| 801 |
} |
| 802 |
} |
| 803 |
} |
| 804 |
const anchorNode = this.document.getSelection()?.anchorNode; |
| 805 |
const isSelectionInProtected = |
| 806 |
this.document.getSelection()?.isCollapsed && |
| 807 |
(isProtecting(anchorNode) || isProtected(anchorNode)); |
| 808 |
if (!selectionData.currentSelectionIsInEditable || isSelectionInProtected) { |
| 809 |
const popoverEl = document.querySelector(".o-we-linkpopover"); |
| 810 |
const anchorNode = document.getSelection()?.anchorNode; |
| 811 |
if ( |
| 812 |
(popoverEl && !selectionData.documentSelection) || |
| 813 |
(anchorNode && isElement(anchorNode) && anchorNode.closest(".o-we-linkpopover")) |
| 814 |
) { |
| 815 |
return; |
| 816 |
} |
| 817 |
this.linkInDocument = null; |
| 818 |
this.closeLinkTools(); |
| 819 |
} else if (!selection.isCollapsed) { |
| 820 |
// Open the link tool only if we have an image selected and the selection |
| 821 |
// is fully contained in the image parent link. |
| 822 |
const imageNode = findInSelection(selection, "img"); |
| 823 |
const parentElement = imageNode?.parentElement; |
| 824 |
const linkContainingImage = imageNode && closestElement(imageNode, "a"); |
| 825 |
if ( |
| 826 |
linkContainingImage && |
| 827 |
this.isLinkAllowedOnSelection() && |
| 828 |
parentElement.contains(selection.anchorNode) && |
| 829 |
parentElement.contains(selection.focusNode) |
| 830 |
) { |
| 831 |
this.openLinkTools(linkContainingImage); |
| 832 |
} else { |
| 833 |
this.linkInDocument = null; |
| 834 |
this.closeLinkTools(); |
| 835 |
} |
| 836 |
} else { |
| 837 |
const closestLinkElement = closestElement(selection.anchorNode, "A"); |
| 838 |
const isLinkEditable = this.getResource("is_link_editable_predicates").some((p) => |
| 839 |
p(closestLinkElement) |
| 840 |
); |
| 841 |
if (closestLinkElement && closestLinkElement.isContentEditable) { |
| 842 |
if (closestLinkElement !== this.linkInDocument || !this.currentOverlay.isOpen) { |
| 843 |
this.openLinkTools(closestLinkElement); |
| 844 |
} |
| 845 |
} else if (isLinkEditable) { |
| 846 |
this.openLinkTools(closestLinkElement); |
| 847 |
} else { |
| 848 |
this.linkInDocument = null; |
| 849 |
this.closeLinkTools(); |
| 850 |
} |
| 851 |
} |
| 852 |
} |
| 853 |
|
| 854 |
/** |
| 855 |
* extend the given link element to include all content from the given selection |
| 856 |
* |
| 857 |
* @param {HTMLLinkElement} linkElement |
| 858 |
* @return {boolean} |
| 859 |
*/ |
| 860 |
extendLinkToSelection(linkElement) { |
| 861 |
this.dependencies.split.splitSelection(); |
| 862 |
const selectedNodes = this.dependencies.selection.getTargetedNodes(); |
| 863 |
let before = linkElement.previousSibling; |
| 864 |
while (before !== null && selectedNodes.includes(before)) { |
| 865 |
linkElement.insertBefore(before, linkElement.firstChild); |
| 866 |
before = linkElement.previousSibling; |
| 867 |
} |
| 868 |
let after = linkElement.nextSibling; |
| 869 |
while (after && selectedNodes.includes(after)) { |
| 870 |
linkElement.appendChild(after); |
| 871 |
after = linkElement.nextSibling; |
| 872 |
} |
| 873 |
this.dependencies.selection.setCursorEnd(linkElement); |
| 874 |
} |
| 875 |
|
| 876 |
isUnremovable(linkEl) { |
| 877 |
return this.getResource("unremovable_node_predicates").some((p) => p(linkEl)); |
| 878 |
} |
| 879 |
|
| 880 |
/** |
| 881 |
* Remove the link from the collapsed selection |
| 882 |
*/ |
| 883 |
removeLinkInDocument(link = this.linkInDocument) { |
| 884 |
if (!link.parentElement.isContentEditable || this.isUnremovable(link)) { |
| 885 |
return; |
| 886 |
} |
| 887 |
const cursors = this.dependencies.selection.preserveSelection(); |
| 888 |
if (link && link.isContentEditable && link.parentElement.isContentEditable) { |
| 889 |
cursors.update(callbacksForCursorUpdate.unwrap(link)); |
| 890 |
unwrapContents(link); |
| 891 |
} |
| 892 |
cursors.restore(); |
| 893 |
this.linkInDocument = null; |
| 894 |
this.dependencies.selection.focusEditable(); |
| 895 |
this.dependencies.history.addStep(); |
| 896 |
} |
| 897 |
|
| 898 |
removeLinkFromSelectionIsDisabled(selection) { |
| 899 |
for (const node of this.dependencies.selection.getTargetedNodes()) { |
| 900 |
const linkEl = closestElement(node, "a"); |
| 901 |
if (linkEl && !this.isLinkImmutable(linkEl) && !this.isUnremovable(linkEl)) { |
| 902 |
return false; |
| 903 |
} |
| 904 |
} |
| 905 |
return true; |
| 906 |
} |
| 907 |
removeLinkFromSelection() { |
| 908 |
const selection = this.dependencies.split.splitSelection(); |
| 909 |
|
| 910 |
// If not, unlink only the part(s) of the link(s) that are selected: |
| 911 |
// `<a>a[b</a>c<a>d</a>e<a>f]g</a>` => `<a>a</a>[bcdef]<a>g</a>`. |
| 912 |
let { anchorNode, focusNode, anchorOffset, focusOffset } = selection; |
| 913 |
const direction = selection.direction; |
| 914 |
// Split the links around the selection. |
| 915 |
let [startLink, endLink] = [ |
| 916 |
closestElement(anchorNode, "a"), |
| 917 |
closestElement(focusNode, "a"), |
| 918 |
]; |
| 919 |
let cursors; |
| 920 |
if (startLink) { |
| 921 |
// If a FEFF character is present as anchorNode or focusNode, |
| 922 |
// restoring the selection later may throw an error. Therefore, |
| 923 |
// FEFF characters should be cleaned before splitting the link. |
| 924 |
cursors = this.dependencies.selection.preserveSelection(); |
| 925 |
this.dependencies.feff.removeFeffs(startLink, cursors); |
| 926 |
cursors.restore(); |
| 927 |
} |
| 928 |
if (endLink && startLink !== endLink) { |
| 929 |
cursors = this.dependencies.selection.preserveSelection(); |
| 930 |
this.dependencies.feff.removeFeffs(endLink, cursors); |
| 931 |
cursors.restore(); |
| 932 |
} |
| 933 |
({ anchorNode, focusNode, anchorOffset, focusOffset } = |
| 934 |
this.dependencies.selection.getEditableSelection()); |
| 935 |
cursors = this.dependencies.selection.preserveSelection(); |
| 936 |
// to remove link from selected images |
| 937 |
let targetedNodes = this.dependencies.selection.getTargetedNodes(); |
| 938 |
const selectedImageNodes = targetedNodes.filter((node) => node.tagName === "IMG"); |
| 939 |
if (selectedImageNodes.length && startLink && endLink && startLink === endLink) { |
| 940 |
for (const imageNode of selectedImageNodes) { |
| 941 |
let imageLink; |
| 942 |
const figure = closestElement(imageNode, "figure"); |
| 943 |
if (direction === DIRECTIONS.RIGHT) { |
| 944 |
imageLink = this.dependencies.split.splitAroundUntil( |
| 945 |
figure || imageNode, |
| 946 |
endLink |
| 947 |
); |
| 948 |
} else { |
| 949 |
imageLink = this.dependencies.split.splitAroundUntil( |
| 950 |
figure || imageNode, |
| 951 |
startLink |
| 952 |
); |
| 953 |
} |
| 954 |
cursors.update(callbacksForCursorUpdate.unwrap(imageLink)); |
| 955 |
unwrapContents(imageLink); |
| 956 |
if (figure && figure.parentElement !== this.editable) { |
| 957 |
// Remove the base container parent if there is one. Figure |
| 958 |
// is a block so it's not needed. |
| 959 |
unwrapContents(figure.parentElement); |
| 960 |
} |
| 961 |
// update the links at the selection |
| 962 |
[startLink, endLink] = [ |
| 963 |
closestElement(anchorNode, "a"), |
| 964 |
closestElement(focusNode, "a"), |
| 965 |
]; |
| 966 |
} |
| 967 |
cursors.restore(); |
| 968 |
// when only unlink an inline image, add step after the unwrapping |
| 969 |
if ( |
| 970 |
selectedImageNodes.length === 1 && |
| 971 |
selectedImageNodes.length === targetedNodes.length |
| 972 |
) { |
| 973 |
this.dependencies.history.addStep(); |
| 974 |
return; |
| 975 |
} |
| 976 |
} |
| 977 |
const startBlock = closestBlock(startLink); |
| 978 |
const endBlock = closestBlock(endLink); |
| 979 |
if ( |
| 980 |
startLink && |
| 981 |
startLink.isConnected && |
| 982 |
startLink.parentElement.isContentEditable && |
| 983 |
!this.isUnremovable(startLink) |
| 984 |
) { |
| 985 |
anchorNode = this.dependencies.split.splitAroundUntil(anchorNode, startLink); |
| 986 |
anchorOffset = direction === DIRECTIONS.RIGHT ? 0 : nodeSize(anchorNode); |
| 987 |
this.dependencies.selection.setSelection( |
| 988 |
{ anchorNode, anchorOffset, focusNode, focusOffset }, |
| 989 |
{ normalize: true } |
| 990 |
); |
| 991 |
} |
| 992 |
// Only split the end link if it was not already done above. |
| 993 |
if ( |
| 994 |
endLink && |
| 995 |
endLink.isConnected && |
| 996 |
endLink.parentElement.isContentEditable && |
| 997 |
!this.isUnremovable(endLink) |
| 998 |
) { |
| 999 |
focusNode = this.dependencies.split.splitAroundUntil( |
| 1000 |
focusNode, |
| 1001 |
closestElement(focusNode, "a") |
| 1002 |
); |
| 1003 |
focusOffset = direction === DIRECTIONS.RIGHT ? nodeSize(focusNode) : 0; |
| 1004 |
this.dependencies.selection.setSelection( |
| 1005 |
{ anchorNode, anchorOffset, focusNode, focusOffset }, |
| 1006 |
{ normalize: true } |
| 1007 |
); |
| 1008 |
} |
| 1009 |
targetedNodes = this.dependencies.selection.getTargetedNodes(); |
| 1010 |
const links = new Set( |
| 1011 |
targetedNodes |
| 1012 |
.map((node) => closestElement(node, "a")) |
| 1013 |
.filter( |
| 1014 |
(a) => |
| 1015 |
a && |
| 1016 |
a.isContentEditable && |
| 1017 |
a.parentElement.isContentEditable && |
| 1018 |
!this.isUnremovable(a) |
| 1019 |
) |
| 1020 |
); |
| 1021 |
if (links.size) { |
| 1022 |
for (const link of links) { |
| 1023 |
cursors.update(callbacksForCursorUpdate.unwrap(link)); |
| 1024 |
unwrapContents(link); |
| 1025 |
} |
| 1026 |
cursors.restore(); |
| 1027 |
} |
| 1028 |
if (startBlock) { |
| 1029 |
// Remove empty links splitted by `splitAroundUntil` due to |
| 1030 |
// adjacent invisible text nodes. |
| 1031 |
this.removeEmptyLinks(startBlock); |
| 1032 |
} |
| 1033 |
if (endBlock && endBlock !== startBlock) { |
| 1034 |
this.removeEmptyLinks(endBlock); |
| 1035 |
} |
| 1036 |
this.dependencies.history.addStep(); |
| 1037 |
} |
| 1038 |
|
| 1039 |
removeEmptyLinks(root) { |
| 1040 |
const remove = (node) => { |
| 1041 |
for (const child of node.childNodes) { |
| 1042 |
remove(child); |
| 1043 |
} |
| 1044 |
if (!this.isUnremovable(node)) { |
| 1045 |
node.before(...node.childNodes); |
| 1046 |
node.remove(); |
| 1047 |
} |
| 1048 |
}; |
| 1049 |
// @todo: preserve spaces |
| 1050 |
for (const link of root.querySelectorAll("a")) { |
| 1051 |
if ( |
| 1052 |
[...link.childNodes].some(isVisible) || |
| 1053 |
!link.parentElement.isContentEditable || |
| 1054 |
this.isUnremovable(link) || |
| 1055 |
this.getResource("legit_empty_link_predicates").some((p) => p(link)) |
| 1056 |
) { |
| 1057 |
continue; |
| 1058 |
} |
| 1059 |
remove(link); |
| 1060 |
} |
| 1061 |
} |
| 1062 |
|
| 1063 |
updateCurrentLinkSyncState() { |
| 1064 |
const { anchorNode } = this.dependencies.selection.getEditableSelection(); |
| 1065 |
const linkEl = closestElement(anchorNode, "a"); |
| 1066 |
if (linkEl && linkEl.isContentEditable) { |
| 1067 |
const label = linkEl.innerText; |
| 1068 |
const url = deduceURLfromText(label, linkEl); |
| 1069 |
const href = linkEl.getAttribute("href"); |
| 1070 |
if ( |
| 1071 |
url && |
| 1072 |
(url === href || url + "/" === href || url === deduceURLfromText(href, linkEl)) |
| 1073 |
) { |
| 1074 |
this.isCurrentLinkInSync = true; |
| 1075 |
} |
| 1076 |
} |
| 1077 |
} |
| 1078 |
|
| 1079 |
onBeforeInput(ev) { |
| 1080 |
if (ev.inputType === "insertParagraph" || ev.inputType === "insertLineBreak") { |
| 1081 |
const nodeForSelectionRestore = this.handleAutomaticLinkInsertion(); |
| 1082 |
if (nodeForSelectionRestore) { |
| 1083 |
this.dependencies.selection.setCursorStart(nodeForSelectionRestore); |
| 1084 |
this.dependencies.history.addStep(); |
| 1085 |
} |
| 1086 |
} |
| 1087 |
if (ev.inputType === "insertText" && ev.data === " ") { |
| 1088 |
const nodeForSelectionRestore = this.handleAutomaticLinkInsertion(); |
| 1089 |
if (nodeForSelectionRestore) { |
| 1090 |
// Since we manually insert a space here, we will be adding a history step |
| 1091 |
// after link creation with selection at the end of the link and another |
| 1092 |
// after inserting the space. So first undo will remove the space, and the |
| 1093 |
// second will undo the link creation. |
| 1094 |
this.dependencies.selection.setSelection({ |
| 1095 |
anchorNode: nodeForSelectionRestore, |
| 1096 |
anchorOffset: 0, |
| 1097 |
}); |
| 1098 |
this.dependencies.history.addStep(); |
| 1099 |
nodeForSelectionRestore.textContent = |
| 1100 |
"\u00A0" + nodeForSelectionRestore.textContent; |
| 1101 |
this.dependencies.selection.setSelection({ |
| 1102 |
anchorNode: nodeForSelectionRestore, |
| 1103 |
anchorOffset: 1, |
| 1104 |
}); |
| 1105 |
this.dependencies.history.addStep(); |
| 1106 |
ev.preventDefault(); |
| 1107 |
} |
| 1108 |
} |
| 1109 |
this.updateCurrentLinkSyncState(); |
| 1110 |
} |
| 1111 |
|
| 1112 |
onInputDeleteNormalizeLink() { |
| 1113 |
const { anchorNode } = this.dependencies.selection.getEditableSelection(); |
| 1114 |
const linkEl = closestElement(anchorNode, "a"); |
| 1115 |
if (linkEl && linkEl.isContentEditable) { |
| 1116 |
const label = linkEl.innerText; |
| 1117 |
const url = deduceURLfromText(label, linkEl); |
| 1118 |
if (url && this.isCurrentLinkInSync) { |
| 1119 |
linkEl.setAttribute("href", url); |
| 1120 |
this.isCurrentLinkInSync = false; |
| 1121 |
if (this.currentOverlay.isOpen) { |
| 1122 |
this.currentOverlay.close(); |
| 1123 |
} |
| 1124 |
} |
| 1125 |
} |
| 1126 |
} |
| 1127 |
onPasteNormalizeLink() { |
| 1128 |
this.updateCurrentLinkSyncState(); |
| 1129 |
this.onInputDeleteNormalizeLink(); |
| 1130 |
} |
| 1131 |
|
| 1132 |
deleteImageLink(imageToDelete) { |
| 1133 |
if ( |
| 1134 |
imageToDelete.parentElement.tagName === "A" && |
| 1135 |
!this.isUnremovable(imageToDelete.parentElement) && |
| 1136 |
imageToDelete.parentElement.parentElement.isContentEditable |
| 1137 |
) { |
| 1138 |
// If the link is empty after removing the image, remove it. |
| 1139 |
const cursors = this.dependencies.selection.preserveSelection(); |
| 1140 |
cursors.update(callbacksForCursorUpdate.remove(imageToDelete)); |
| 1141 |
imageToDelete.remove(); |
| 1142 |
this.closeLinkTools(cursors); |
| 1143 |
this.dependencies.history.addStep(); |
| 1144 |
return true; |
| 1145 |
} |
| 1146 |
return false; |
| 1147 |
} |
| 1148 |
|
| 1149 |
/** |
| 1150 |
* Inserts a link in the editor. Called after pressing space or (shif +) enter. |
| 1151 |
* Performs a regex check to determine if the url has correct syntax. |
| 1152 |
*/ |
| 1153 |
handleAutomaticLinkInsertion() { |
| 1154 |
let selection = this.dependencies.selection.getEditableSelection(); |
| 1155 |
if ( |
| 1156 |
isHtmlContentSupported(selection) && |
| 1157 |
!closestElement(selection.anchorNode, "a") && |
| 1158 |
selection.anchorNode.nodeType === Node.TEXT_NODE |
| 1159 |
) { |
| 1160 |
// Merge adjacent text nodes. |
| 1161 |
selection.anchorNode.parentNode.normalize(); |
| 1162 |
selection = this.dependencies.selection.getEditableSelection(); |
| 1163 |
const textSliced = selection.anchorNode.textContent.slice(0, selection.anchorOffset); |
| 1164 |
const textNodeSplitted = textSliced.split(/\s/); |
| 1165 |
const potentialUrl = textNodeSplitted.pop(); |
| 1166 |
// In case of multiple matches, only the last one will be converted. |
| 1167 |
const match = [...potentialUrl.matchAll(new RegExp(URL_REGEX, "g"))].pop(); |
| 1168 |
|
| 1169 |
if (match && !EMAIL_REGEX.test(match[0])) { |
| 1170 |
const nodeForSelectionRestore = selection.anchorNode.splitText( |
| 1171 |
selection.anchorOffset |
| 1172 |
); |
| 1173 |
const url = match[2] ? match[0] : "https://" + match[0]; |
| 1174 |
const startOffset = selection.anchorOffset - potentialUrl.length + match.index; |
| 1175 |
const text = selection.anchorNode.textContent.slice( |
| 1176 |
startOffset, |
| 1177 |
startOffset + match[0].length |
| 1178 |
); |
| 1179 |
const link = this.createLink(url, text); |
| 1180 |
// split the text node and replace the url text with the link |
| 1181 |
const textNodeToReplace = selection.anchorNode.splitText(startOffset); |
| 1182 |
textNodeToReplace.splitText(match[0].length); |
| 1183 |
selection.anchorNode.parentElement.replaceChild(link, textNodeToReplace); |
| 1184 |
if (link.getAttribute("href") === link.textContent) { |
| 1185 |
this.newlyInsertedLinks.add(link); |
| 1186 |
} |
| 1187 |
return nodeForSelectionRestore; |
| 1188 |
} |
| 1189 |
} |
| 1190 |
} |
| 1191 |
|
| 1192 |
/** |
| 1193 |
* Special behavior for links: do not break the link at its edges, but |
| 1194 |
* rather before/after it. |
| 1195 |
* |
| 1196 |
* @param {Object} params |
| 1197 |
* @param {Element} params.targetNode |
| 1198 |
* @param {number} params.targetOffset |
| 1199 |
* @param {Element} params.blockToSplit |
| 1200 |
*/ |
| 1201 |
handleSplitBlock(params) { |
| 1202 |
return this.handleEnterAtEdgeOfLink(params, this.dependencies.split.splitElementBlock); |
| 1203 |
} |
| 1204 |
|
| 1205 |
/** |
| 1206 |
* Special behavior for links: do not add a line break at its edges, but |
| 1207 |
* rather outside it. |
| 1208 |
* |
| 1209 |
* @param {Object} params |
| 1210 |
* @param {Element} params.targetNode |
| 1211 |
* @param {number} params.targetOffset |
| 1212 |
*/ |
| 1213 |
handleInsertLineBreak(params) { |
| 1214 |
return this.handleEnterAtEdgeOfLink( |
| 1215 |
params, |
| 1216 |
this.dependencies.lineBreak.insertLineBreakElement |
| 1217 |
); |
| 1218 |
} |
| 1219 |
|
| 1220 |
/** |
| 1221 |
* @param {Object} params |
| 1222 |
* @param {Element} params.targetNode |
| 1223 |
* @param {number} params.targetOffset |
| 1224 |
* @param {Element} [params.blockToSplit] |
| 1225 |
* @param {Function} splitOrLineBreakCallback |
| 1226 |
*/ |
| 1227 |
handleEnterAtEdgeOfLink(params, splitOrLineBreakCallback) { |
| 1228 |
// @todo: handle target Node being a descendent of a link (iterate over |
| 1229 |
// leaves inside the link, rather than childNodes) |
| 1230 |
let { targetNode, targetOffset, blockToSplit } = params; |
| 1231 |
if (targetNode.tagName !== "A") { |
| 1232 |
return; |
| 1233 |
} |
| 1234 |
const edge = isPositionAtEdgeofLink(targetNode, targetOffset); |
| 1235 |
if (!edge) { |
| 1236 |
return; |
| 1237 |
} |
| 1238 |
[targetNode, targetOffset] = edge === "start" ? leftPos(targetNode) : rightPos(targetNode); |
| 1239 |
blockToSplit = targetNode; |
| 1240 |
splitOrLineBreakCallback({ ...params, targetNode, targetOffset, blockToSplit }); |
| 1241 |
return true; |
| 1242 |
} |
| 1243 |
|
| 1244 |
handleAfterInsert(insertedNodes) { |
| 1245 |
for (const node of insertedNodes) { |
| 1246 |
if (node.nodeType === Node.ELEMENT_NODE) { |
| 1247 |
for (const link of selectElements(node, "A")) { |
| 1248 |
if (link.getAttribute("href") === link.textContent && !this.isImage) { |
| 1249 |
this.newlyInsertedLinks.add(link); |
| 1250 |
} |
| 1251 |
} |
| 1252 |
} |
| 1253 |
} |
| 1254 |
} |
| 1255 |
|
| 1256 |
initializePopovers() { |
| 1257 |
this.overlays = []; |
| 1258 |
this.getResource("link_popovers").map((link_popover) => { |
| 1259 |
this.overlays.push({ |
| 1260 |
overlay: this.dependencies.overlay.createOverlay( |
| 1261 |
link_popover.PopoverClass, |
| 1262 |
{ |
| 1263 |
closeOnPointerdown: true, |
| 1264 |
}, |
| 1265 |
{ |
| 1266 |
sequence: 50, |
| 1267 |
} |
| 1268 |
), |
| 1269 |
isAvailable: link_popover.isAvailable, |
| 1270 |
getProps: link_popover.getProps, |
| 1271 |
}); |
| 1272 |
}); |
| 1273 |
} |
| 1274 |
|
| 1275 |
getActivePopover(linkElement) { |
| 1276 |
return this.overlays.find((overlay) => overlay.isAvailable(linkElement)); |
| 1277 |
} |
| 1278 |
|
| 1279 |
isLinkImmutable(linkEl) { |
| 1280 |
return this.getResource("immutable_link_selectors").some((s) => linkEl.matches(s)); |
| 1281 |
} |
| 1282 |
|
| 1283 |
doubleClickLinkOverrides(ev) { |
| 1284 |
const clickedLink = closestElement(ev.target, "a"); |
| 1285 |
// If we double click on a link, limit the selection inside the link |
| 1286 |
if (clickedLink) { |
| 1287 |
// mimic the double click behavior of browsers |
| 1288 |
this.dependencies.selection.modifySelection("extend", "backward", "word"); |
| 1289 |
this.document.getSelection().collapseToStart(); |
| 1290 |
this.dependencies.selection.modifySelection("extend", "forward", "word"); |
| 1291 |
|
| 1292 |
const { anchorNode, focusNode, anchorOffset, focusOffset } = |
| 1293 |
this.dependencies.selection.getEditableSelection(); |
| 1294 |
|
| 1295 |
// We reset the word selection of double click to be inside the current clicked link |
| 1296 |
// when it spreads over different links. Because it's a word selection, we need to keep |
| 1297 |
// the correct offsets when resetting. |
| 1298 |
if (clickedLink.contains(anchorNode) && !clickedLink.contains(focusNode)) { |
| 1299 |
this.dependencies.selection.setSelection({ |
| 1300 |
anchorNode, |
| 1301 |
anchorOffset, |
| 1302 |
focusNode: clickedLink, |
| 1303 |
focusOffset: nodeSize(clickedLink) - 1, // -1 to avoid the FEFF char |
| 1304 |
}); |
| 1305 |
} else if (!clickedLink.contains(anchorNode) && clickedLink.contains(focusNode)) { |
| 1306 |
this.dependencies.selection.setSelection({ |
| 1307 |
anchorNode: clickedLink, |
| 1308 |
anchorOffset: 1, // 1 to avoid the FEFF char |
| 1309 |
focusNode, |
| 1310 |
focusOffset, |
| 1311 |
}); |
| 1312 |
} else if (!clickedLink.contains(anchorNode) && !clickedLink.contains(focusNode)) { |
| 1313 |
this.dependencies.selection.setSelection({ |
| 1314 |
anchorNode: clickedLink, |
| 1315 |
anchorOffset: 1, // 1 to avoid the FEFF char |
| 1316 |
focusNode: clickedLink, |
| 1317 |
focusOffset: nodeSize(clickedLink) - 1, // -1 to avoid the FEFF char |
| 1318 |
}); |
| 1319 |
} else { |
| 1320 |
this.dependencies.selection.setSelection({ |
| 1321 |
anchorNode, |
| 1322 |
anchorOffset, |
| 1323 |
focusNode, |
| 1324 |
focusOffset, |
| 1325 |
}); |
| 1326 |
} |
| 1327 |
|
| 1328 |
return true; |
| 1329 |
} |
| 1330 |
} |
| 1331 |
|
| 1332 |
tripleClickButtonOverrides(ev) { |
| 1333 |
const selection = this.dependencies.selection.getEditableSelection(); |
| 1334 |
const buttonElement = isBrowserFirefox() |
| 1335 |
? findInSelection(selection, "a.btn") |
| 1336 |
: closestElement(selection.anchorNode, "a.btn"); |
| 1337 |
if (buttonElement) { |
| 1338 |
this.dependencies.selection.setSelection({ |
| 1339 |
anchorNode: buttonElement, |
| 1340 |
anchorOffset: 0, |
| 1341 |
focusNode: buttonElement, |
| 1342 |
focusOffset: nodeSize(buttonElement), |
| 1343 |
}); |
| 1344 |
ev.preventDefault(); |
| 1345 |
return true; |
| 1346 |
} |
| 1347 |
} |
| 1348 |
} |