Debian Codegraph @

addons/html_editor/static/src/main/link/link_popover.js

raw
1 import { session } from "@web/session";
2 import { _t } from "@web/core/l10n/translation";
3 import { Component, useState, useRef, useEffect, useExternalListener } from "@odoo/owl";
4 import { useService } from "@web/core/utils/hooks";
5 import { browser } from "@web/core/browser/browser";
6 import { cleanZWChars, deduceURLfromText } from "./utils";
7 import { useColorPicker } from "@web/core/color_picker/color_picker";
8 import { CheckBox } from "@web/core/checkbox/checkbox";
9
10 const DEFAULT_CUSTOM_TEXT_COLOR = "#714B67";
11 const DEFAULT_CUSTOM_FILL_COLOR = "#ffffff";
12
13 const isCSSVariable = (color) => color.match(/^o-color-\d$|^\d{3}$/);
14 const formatColor = (color) => {
15 if (color.match(/^o-color-\d$/gm)) {
16 return `var(--hb-cp-${color})`;
17 }
18 if (color.match(/^\d{3}$/gm)) {
19 return `var(--${color})`;
20 }
21 return color;
22 };
23
24 export class LinkPopover extends Component {
25 static template = "html_editor.linkPopover";
26 static props = {
27 document: { validate: (p) => p.nodeType === Node.DOCUMENT_NODE },
28 linkElement: { validate: (el) => el.nodeType === Node.ELEMENT_NODE },
29 onApply: Function,
30 onChange: Function,
31 onDiscard: Function,
32 onRemove: Function,
33 onCopy: Function,
34 onEdit: Function,
35 getInternalMetaData: Function,
36 getExternalMetaData: Function,
37 getAttachmentMetadata: Function,
38 isImage: Boolean,
39 showReplaceTitleBanner: Boolean,
40 type: String,
41 LinkPopoverState: Object,
42 recordInfo: Object,
43 canEdit: { type: Boolean, optional: true },
44 canRemove: { type: Boolean, optional: true },
45 canUpload: { type: Boolean, optional: true },
46 onUpload: { type: Function, optional: true },
47 allowCustomStyle: { type: Boolean, optional: true },
48 allowTargetBlank: { type: Boolean, optional: true },
49 allowStripDomain: { type: Boolean, optional: true },
50 formatColor: { type: Function, optional: true },
51 };
52 static defaultProps = {
53 canEdit: true,
54 canRemove: true,
55 formatColor: formatColor,
56 };
57 static components = { CheckBox };
58 colorsData = [
59 { type: "", label: _t("Link"), btnPreview: "link" },
60 { type: "primary", label: _t("Button Primary"), btnPreview: "primary" },
61 { type: "secondary", label: _t("Button Secondary"), btnPreview: "secondary" },
62 { type: "custom", label: _t("Custom"), btnPreview: "custom" },
63 // Note: by compatibility the dialog should be able to remove old
64 // colors that were suggested like the BS status colors or the
65 // alpha -> epsilon classes. This is currently done by removing
66 // all btn-* classes anyway.
67 ];
68 buttonSizesData = [
69 { size: "sm", label: _t("Small") },
70 { size: "", label: _t("Medium") },
71 { size: "lg", label: _t("Large") },
72 ];
73 borderData = [
74 { style: "solid", label: "━━━" },
75 { style: "dashed", label: "╌╌╌" },
76 { style: "dotted", label: "┄┄┄" },
77 { style: "double", label: "═══" },
78 ];
79 buttonShapeData = [
80 { shape: "", label: "Default" },
81 { shape: "rounded-circle", label: "Default + Rounded" },
82 { shape: "outline", label: "Outline" },
83 { shape: "outline rounded-circle", label: "Outline + Rounded" },
84 { shape: "fill", label: "Fill" },
85 { shape: "fill rounded-circle", label: "Fill + Rounded" },
86 { shape: "flat", label: "Flat" },
87 ];
88 setup() {
89 this.ui = useService("ui");
90 this.notificationService = useService("notification");
91 this.uploadService = useService("uploadLocalFiles");
92
93 const linkElement = this.props.linkElement;
94 const textContent = cleanZWChars(linkElement.textContent);
95 const labelEqualsUrl =
96 textContent === linkElement.getAttribute("href") ||
97 textContent + "/" === linkElement.getAttribute("href");
98
99 const computedStyle = this.props.document.defaultView.getComputedStyle(linkElement);
100 const currentRelValues = linkElement.rel.split(" ");
101 this.state = useState({
102 editing: this.props.LinkPopoverState.editing,
103 // `.getAttribute("href")` instead of `.href` to keep relative url
104 url: linkElement.getAttribute("href") || this.deduceUrl(textContent),
105 label: labelEqualsUrl ? "" : textContent,
106 previewIcon: {
107 /** @type {'fa'|'imgSrc'|'mimetype'} */
108 type: "fa",
109 value: "fa-globe",
110 },
111 urlTitle: "",
112 urlDescription: "",
113 linkPreviewName: "",
114 imgSrc: "",
115 type:
116 this.props.type ||
117 linkElement.className.match(/btn(-[a-z0-9_-]*)(primary|secondary|custom)/)?.pop() ||
118 "",
119 linkTarget: linkElement.target === "_blank" ? "_blank" : "",
120 directDownload: true,
121 isDocument: false,
122 buttonSize: linkElement.className.match(/btn-(sm|lg)/)?.[1] || "",
123 buttonShape: this.getButtonShape(),
124 customBorderSize: computedStyle.borderWidth.replace("px", "") || "0",
125 customBorderStyle: computedStyle.borderStyle || "solid",
126 isImage: this.props.isImage,
127 showReplaceTitleBanner: this.props.showReplaceTitleBanner,
128 showLabel: !linkElement.childElementCount,
129 stripDomain: true,
130 showAdvancedOptions: false,
131 relAttributeOptions: {
132 nofollow: {
133 label: "nofollow",
134 description: _t("Tells search engines not to follow this link"),
135 isChecked: currentRelValues.includes("nofollow"),
136 },
137 noreferrer: {
138 label: "noreferrer",
139 description: _t("Removes referrer information sent to the target site"),
140 isChecked: currentRelValues.includes("noreferrer"),
141 },
142 sponsored: {
143 label: "sponsored",
144 description: _t("Indicates the link is sponsored or paid content"),
145 isChecked: currentRelValues.includes("sponsored"),
146 },
147 noopener: {
148 label: "noopener",
149 description: _t(
150 "Prevents the new page from accessing the original window (security)"
151 ),
152 isChecked: currentRelValues.includes("noopener"),
153 },
154 },
155 });
156
157 const getTargetedElements = () => [this.props.linkElement];
158 this.customTextColorState = useState({
159 selectedColor: computedStyle.color || DEFAULT_CUSTOM_TEXT_COLOR,
160 defaultTab: "solid",
161 getTargetedElements,
162 mode: "color",
163 });
164 this.customTextResetPreviewColor = this.customTextColorState.selectedColor;
165 this.customFillColorState = useState({
166 selectedColor:
167 (computedStyle.backgroundImage === "none"
168 ? undefined
169 : computedStyle.backgroundImage) ||
170 computedStyle.backgroundColor ||
171 DEFAULT_CUSTOM_FILL_COLOR,
172 defaultTab: "solid",
173 getTargetedElements,
174 mode: "background-color",
175 });
176 this.customFillResetPreviewColor = this.customFillColorState.selectedColor;
177 this.customBorderColorState = useState({
178 selectedColor: computedStyle.borderColor || DEFAULT_CUSTOM_TEXT_COLOR,
179 defaultTab: "solid",
180 getTargetedElements,
181 mode: "border-color",
182 });
183 this.customBorderResetPreviewColor = this.customBorderColorState.selectedColor;
184
185 if (this.props.allowCustomStyle) {
186 const createCustomColorPicker = (refName, colorStateRef, resetValueRef) =>
187 useColorPicker(
188 refName,
189 {
190 state: this[colorStateRef],
191 enabledTabs:
192 colorStateRef === "customFillColorState"
193 ? ["solid", "custom", "gradient"]
194 : ["solid", "custom"],
195 getUsedCustomColors: () => [],
196 colorPrefix: "",
197 cssVarColorPrefix: "hb-cp-",
198 applyColor: (colorValue) => {
199 this[colorStateRef].selectedColor = colorValue;
200 this[resetValueRef] = colorValue;
201 },
202 applyColorPreview: (colorValue) => {
203 this[colorStateRef].selectedColor = colorValue;
204 this.onChange();
205 },
206 applyColorResetPreview: () => {
207 this[colorStateRef].selectedColor = this[resetValueRef];
208 this.onChange();
209 },
210 },
211 {
212 env: this.__owl__.childEnv,
213 // `useOverlayServiceOffset` adds 1000 to each sequence value to solve
214 // overlay visibility in `iframe`, here we increment default sequence (50)
215 // by 1 and we add 1000 to have color picker always on top of all overlays.
216 sequence: 1051,
217 }
218 );
219 this.customTextColorPicker = createCustomColorPicker(
220 "customTextColorButton",
221 "customTextColorState",
222 "customTextResetPreviewColor"
223 );
224 this.customFillColorPicker = createCustomColorPicker(
225 "customFillColorButton",
226 "customFillColorState",
227 "customFillResetPreviewColor"
228 );
229 this.customBorderColorPicker = createCustomColorPicker(
230 "customBorderColorButton",
231 "customBorderColorState",
232 "customBorderResetPreviewColor"
233 );
234 }
235 this.updateDocumentState();
236 this.editingWrapper = useRef("editing-wrapper");
237 this.inputRef = useRef(
238 this.state.isImage || (this.state.label && !this.state.url) ? "url" : "label"
239 );
240 useEffect(
241 (el) => {
242 if (el) {
243 el.focus();
244 }
245 },
246 () => [this.inputRef.el]
247 );
248 if (!this.state.editing) {
249 this.loadAsyncLinkPreview();
250 }
251 const onPointerDown = (ev) => {
252 if (this.state.isImage) {
253 return;
254 }
255 this.state.url ||= "#";
256 if (this.editingWrapper?.el && !this.editingWrapper.el.contains(ev.target)) {
257 this.onClickApply();
258 }
259 };
260 useExternalListener(this.props.document, "pointerdown", onPointerDown);
261 if (this.props.document !== document) {
262 // Listen to pointerdown outside the iframe
263 useExternalListener(document, "pointerdown", onPointerDown);
264 }
265 }
266
267 toggleAdvancedOptions() {
268 this.state.showAdvancedOptions = !this.state.showAdvancedOptions;
269 }
270
271 toggleRelAttr(attr) {
272 const option = this.state.relAttributeOptions[attr];
273 option.isChecked = !option.isChecked;
274 }
275
276 onChange() {
277 // Apply changes to update the link preview.
278 this.props.onChange(
279 this.state.url,
280 this.state.label,
281 this.classes,
282 this.customStyles,
283 this.state.linkTarget,
284 this.state.attachmentId
285 );
286 this.updateDocumentState();
287 }
288 onClickApply() {
289 const relOptions = this.state.relAttributeOptions;
290 const relValue = Object.keys(relOptions)
291 .filter((key) => relOptions[key].isChecked)
292 .join(" ");
293 this.state.editing = false;
294 this.applyDeducedUrl();
295 this.props.onApply(
296 this.state.url,
297 this.state.label,
298 this.classes,
299 this.customStyles,
300 this.state.linkTarget,
301 this.state.attachmentId,
302 relValue
303 );
304 }
305 applyDeducedUrl() {
306 if (this.state.label === "") {
307 this.state.label = this.state.url;
308 }
309 const deducedUrl = this.deduceUrl(this.state.url);
310 this.state.url = deducedUrl
311 ? this.correctLink(deducedUrl)
312 : this.correctLink(this.state.url);
313 if (
314 this.props.allowStripDomain &&
315 this.state.stripDomain &&
316 this.isAbsoluteURLInCurrentDomain()
317 ) {
318 const urlObj = new URL(this.state.url, window.location.origin);
319 // Not necessarily equal to window.location.origin
320 // (see isAbsoluteURLInCurrentDomain)
321 this.state.url = this.state.url.replace(urlObj.origin, "");
322 }
323 }
324 onClickEdit() {
325 this.state.editing = true;
326 this.props.onEdit();
327 this.updateUrlAndLabel();
328 }
329 updateUrlAndLabel() {
330 this.state.url = this.props.linkElement.getAttribute("href");
331
332 const textContent = cleanZWChars(this.props.linkElement.textContent);
333 const labelEqualsUrl =
334 textContent === this.props.linkElement.getAttribute("href") ||
335 textContent + "/" === this.props.linkElement.getAttribute("href");
336 this.state.label = labelEqualsUrl ? "" : textContent;
337 }
338 // TODO: remove in master
339 async onClickCopy(ev) {
340 ev.preventDefault();
341 await browser.navigator.clipboard.writeText(this.props.linkElement.href || "");
342 this.notificationService.add(_t("Link copied to clipboard."), {
343 type: "success",
344 });
345 this.props.onCopy();
346 }
347 onClickRemove() {
348 this.props.onRemove();
349 }
350
351 onKeydownEnter(ev) {
352 const isAutoCompleteDropdownOpen = document.querySelector(".o-autocomplete--dropdown-menu");
353 if (ev.key === "Enter" && !isAutoCompleteDropdownOpen && this.state.url) {
354 ev.preventDefault();
355 this.onClickApply();
356 }
357 }
358
359 onKeydown(ev) {
360 if (ev.key === "Escape") {
361 ev.preventDefault();
362 ev.stopImmediatePropagation();
363 this.onClickApply();
364 } else if (ev.key == "Tab") {
365 ev.preventDefault();
366 const focusableElements = [
367 ...this.editingWrapper.el.querySelectorAll("input, select, button:not([disabled])"),
368 ];
369 const currentIndex = focusableElements.indexOf(document.activeElement);
370 const nextIndex =
371 (currentIndex + (ev.shiftKey ? -1 : 1) + focusableElements.length) %
372 focusableElements.length;
373 focusableElements[nextIndex].focus();
374 }
375 }
376
377 onInput() {
378 this.onChange();
379 }
380
381 onClickReplaceTitle() {
382 this.state.label = this.state.urlTitle;
383 this.onClickApply();
384 }
385
386 onClickDirectDownload(checked) {
387 this.state.directDownload = checked;
388 this.state.url = this.state.url.replace("&download=true", "");
389 if (this.state.directDownload) {
390 this.state.url += "&download=true";
391 }
392 }
393
394 onClickNewWindow(checked) {
395 this.state.linkTarget = checked ? "_blank" : "";
396 if (!checked) {
397 this.state.relAttributeOptions.noopener.isChecked = false;
398 }
399 }
400
401 onClickStripDomain(checked) {
402 this.state.stripDomain = checked;
403 }
404
405 /**
406 * @private
407 */
408 async updateDocumentState() {
409 const url = this.state.url;
410 const urlObject = URL.parse(url, document.URL);
411 if (
412 url &&
413 (url.startsWith("/web/content/") ||
414 (urlObject &&
415 urlObject.pathname.startsWith("/web/content") &&
416 urlObject.host === document.location.host))
417 ) {
418 const { type } = await this.props.getAttachmentMetadata(url);
419 this.state.isDocument = type !== "url";
420 this.state.directDownload = url.includes("&download=true");
421 } else {
422 this.state.isDocument = false;
423 this.state.directDownload = true;
424 }
425 }
426 correctLink(url) {
427 if (
428 url &&
429 !url.startsWith("tel:") &&
430 !url.startsWith("mailto:") &&
431 !url.includes("://") &&
432 !url.startsWith("/") &&
433 !url.startsWith("#") &&
434 !url.startsWith("${")
435 ) {
436 url = "https://" + url;
437 }
438 if (url && (url.startsWith("http:") || url.startsWith("https:"))) {
439 url = URL.parse(url) ? url : "";
440 }
441 return url;
442 }
443 deduceUrl(text) {
444 text = text.trim();
445 if (/^(https?:|mailto:|tel:)/.test(text)) {
446 // Text begins with a known protocol, accept it as valid URL.
447 return text;
448 } else {
449 return deduceURLfromText(text, this.props.linkElement) || "";
450 }
451 }
452 getButtonShape() {
453 const shapeToRegex = (shape) => {
454 const parts = shape.trim().split(/\s+/);
455 const regexParts = parts.map((cls) => {
456 if (["outline", "fill"].includes(cls)) {
457 cls = `btn-${cls}`;
458 }
459 return `(?=.*\\b${cls}\\b)`;
460 });
461 return { regex: new RegExp(regexParts.join("")), nbParts: parts.length };
462 };
463 // If multiple shapes match, prefer the one with more specificity.
464 let shapeMatched = "";
465 let matchScore = 0;
466 for (const { shape } of this.buttonShapeData) {
467 if (!shape) {
468 continue;
469 }
470 const { regex, nbParts } = shapeToRegex(shape);
471 if (regex.test(this.props.linkElement.className)) {
472 if (matchScore < nbParts) {
473 matchScore = nbParts;
474 shapeMatched = shape;
475 }
476 }
477 }
478 return shapeMatched;
479 }
480 /**
481 * link preview in the popover
482 */
483 resetPreview() {
484 this.state.previewIcon = { type: "fa", value: "fa-globe" };
485 this.state.urlTitle = this.state.url || _t("No URL specified");
486 this.state.urlDescription = "";
487 this.state.linkPreviewName = "";
488 }
489 async loadAsyncLinkPreview() {
490 let url;
491 if (this.state.url === "") {
492 this.resetPreview();
493 this.state.previewIcon.value = "fa-question-circle-o";
494 return;
495 }
496 if (this.isLogoutUrl()) {
497 // The session ends if we fetch this url, so the preview is hardcoded
498 this.resetPreview();
499 this.state.urlTitle = _t("Logout");
500 this.state.previewIcon.value = "fa-sign-out";
501 return;
502 }
503 if (this.isAttachmentUrl()) {
504 const { name, mimetype } = await this.props.getAttachmentMetadata(this.state.url);
505 this.resetPreview();
506 this.state.urlTitle = name;
507 this.state.previewIcon = { type: "mimetype", value: mimetype };
508 return;
509 }
510 try {
511 url = new URL(this.state.url, document.URL); // relative to absolute
512 } catch {
513 // Invalid URL, might happen with editor unsuported protocol. eg type
514 // `geo:37.786971,-122.399677`, become `http://geo:37.786971,-122.399677`
515 this.notificationService.add(_t("This URL is invalid. Preview couldn't be updated."), {
516 type: "danger",
517 });
518 return;
519 }
520 this.resetPreview();
521 const protocol = url.protocol;
522 if (!protocol.startsWith("http")) {
523 const faMap = { "mailto:": "fa-envelope-o", "tel:": "fa-phone" };
524 const icon = faMap[protocol];
525 if (icon) {
526 this.state.previewIcon.value = icon;
527 }
528 } else if (
529 window.location.hostname !== url.hostname &&
530 !new RegExp(`^https?://${session.db}\\.odoo\\.com(/.*)?$`).test(url.origin)
531 ) {
532 // Preview pages from current website only. External website will
533 // most of the time raise a CORS error. To avoid that error, we
534 // would need to fetch the page through the server (s2s), involving
535 // enduser fetching problematic pages such as illicit content.
536 this.state.previewIcon = {
537 type: "imgSrc",
538 value: `https://www.google.com/s2/favicons?sz=16&domain=${encodeURIComponent(url)}`,
539 };
540
541 const externalMetadata = await this.props
542 .getExternalMetaData(this.state.url)
543 .catch((error) => {
544 console.warn(`Error fetching external metadata for ${url.href}:`, error);
545 return {};
546 });
547
548 this.state.urlTitle = externalMetadata?.og_title || this.state.url;
549 this.state.urlDescription = externalMetadata?.og_description || "";
550 this.state.imgSrc = externalMetadata?.og_image || "";
551 if (
552 externalMetadata?.og_image &&
553 this.state.label &&
554 this.state.urlTitle === this.state.url
555 ) {
556 this.state.urlTitle = this.state.label;
557 }
558 } else {
559 // Set state based on cached link meta data
560 // for record missing errors, we push a warning that the url is likely invalid
561 // for other errors, we log them to not block the ui
562 const internalMetadata = await this.props
563 .getInternalMetaData(url.href)
564 .catch((error) => {
565 console.warn(`Error fetching internal metadata for ${url.href}:`, error);
566 return {};
567 });
568 if (internalMetadata.favicon) {
569 this.state.previewIcon = {
570 type: "imgSrc",
571 value: internalMetadata.favicon.href,
572 };
573 }
574 if (internalMetadata.error_msg) {
575 this.notificationService.add(internalMetadata.error_msg, {
576 type: "warning",
577 });
578 } else if (internalMetadata.other_error_msg) {
579 console.error(
580 "Internal meta data retrieve error for link preview: " +
581 internalMetadata.other_error_msg
582 );
583 } else {
584 this.state.linkPreviewName =
585 internalMetadata.link_preview_name ||
586 internalMetadata.display_name ||
587 internalMetadata.name;
588 this.state.urlDescription = internalMetadata?.description || "";
589 this.state.urlTitle = this.state.linkPreviewName
590 ? this.state.linkPreviewName
591 : this.state.url;
592 }
593
594 if (
595 (internalMetadata.ogTitle || internalMetadata.title) &&
596 !this.state.linkPreviewName
597 ) {
598 this.state.urlTitle = internalMetadata.ogTitle
599 ? internalMetadata.ogTitle.getAttribute("content")
600 : internalMetadata.title.text.trim();
601 }
602 }
603 }
604
605 get classes() {
606 const classes = [...this.props.linkElement.classList].filter(
607 (value) => !value.match(/^(btn.*|rounded-circle|flat|(text|bg)-(o-color-\d$|\d{3}$))$/)
608 );
609
610 let stylePrefix = "";
611 if (this.state.type) {
612 if (this.state.buttonSize) {
613 classes.push(`btn-${this.state.buttonSize}`);
614 }
615
616 if (this.state.buttonShape) {
617 const buttonShape = this.state.buttonShape.split(" ");
618 if (["outline", "fill"].includes(buttonShape[0])) {
619 stylePrefix = `${buttonShape[0]}-`;
620 }
621 classes.push(buttonShape.slice(stylePrefix ? 1 : 0).join(" "));
622 }
623
624 classes.push(`btn`, `btn-${stylePrefix}${this.state.type}`);
625 }
626
627 const textColor = this.customTextColorState.selectedColor;
628 if (isCSSVariable(textColor)) {
629 classes.push(`text-${textColor}`);
630 }
631
632 const fillColor = this.customFillColorState.selectedColor;
633 if (isCSSVariable(fillColor)) {
634 classes.push(`bg-${fillColor}`);
635 }
636
637 // Ensure single space between classes
638 return classes.filter(Boolean).join(" ");
639 }
640
641 get customStyles() {
642 if (!this.props.allowCustomStyle || this.state.type !== "custom") {
643 return false;
644 }
645 let customStyles = "";
646
647 const textColor = this.customTextColorState.selectedColor;
648 if (!isCSSVariable(textColor)) {
649 customStyles += `color: ${textColor}; `;
650 }
651
652 const fillColor = this.customFillColorState.selectedColor;
653 if (!isCSSVariable(fillColor)) {
654 const backgroundProperty = fillColor.includes("gradient")
655 ? "background-image"
656 : "background-color";
657 customStyles += `${backgroundProperty}: ${fillColor}; `;
658 }
659
660 const borderColor = this.customBorderColorState.selectedColor;
661 customStyles += `border-width: ${this.state.customBorderSize}px; `;
662 customStyles += `border-color: ${formatColor(borderColor)}; `;
663 customStyles += `border-style: ${this.state.customBorderStyle}; `;
664
665 return customStyles;
666 }
667
668 async uploadFile() {
669 const { upload, getURL } = this.uploadService;
670 const { resModel, resId } = this.props.recordInfo;
671 const [attachment] = await upload({ resModel, resId, accessToken: true });
672 if (!attachment) {
673 // No file selected or upload failed
674 return;
675 }
676 this.props.onUpload?.(attachment);
677 this.state.url = getURL(attachment, { download: true, unique: true, accessToken: true });
678 this.state.label ||= attachment.name;
679 this.state.attachmentId = attachment.id;
680 this.onChange();
681 }
682
683 isLogoutUrl() {
684 return !!this.state.url.match(/\/web\/session\/logout\b/);
685 }
686 isAttachmentUrl() {
687 return !!this.state.url.match(/\/web\/content\/\d+/);
688 }
689 /**
690 * Checks if the given URL is using the domain where the content being
691 * edited is reachable, i.e. if this URL should be stripped of its domain
692 * part and converted to a relative URL if put as a link in the content.
693 *
694 * @private
695 * @returns {boolean}
696 */
697 isAbsoluteURLInCurrentDomain() {
698 // First check if it is a relative URL: if it is, we don't want to check
699 // further as we will always leave those untouched.
700 let hasProtocol;
701 try {
702 hasProtocol = !!new URL(this.state.url).protocol;
703 } catch {
704 hasProtocol = false;
705 }
706 if (!hasProtocol) {
707 return false;
708 }
709
710 const urlObj = new URL(this.state.url, window.location.origin);
711 // Chosen heuristic to detect someone trying to enter a link using
712 // its Odoo instance domain. We just suppose it should be a relative
713 // URL (if unexpected behavior, the user can just not enter its Odoo
714 // instance domain but its real domain, or opt-out from the domain
715 // stripping). Mentioning an .odoo.com domain, especially its own
716 // one, is always a bad practice anyway.
717 return (
718 urlObj.origin === window.location.origin ||
719 new RegExp(`^https?://${session.db}\\.odoo\\.com(/.*)?$`).test(urlObj.origin)
720 );
721 }
722 }