nhn / tui.editor

🍞📝 Markdown WYSIWYG Editor. GFM Standard + Chart & UML Extensible.
http://ui.toast.com/tui-editor
MIT License
17.12k stars 1.74k forks source link

Disabled to access to a link without attaching http protocol #3120

Open DannaJo opened 1 year ago

DannaJo commented 1 year ago

Describe the bug

Inserting a link in editor without http protocol, I cannot move to a link attached in Viewer. (instead move to www.mydomain.com/${link}) (ex. google.com is not working but https://google.com is working)

To Reproduce

Steps to reproduce the behavior:

  1. Go to the viewer
  2. Click on insert link
  3. paste a link (test 2 links. the former is with https and the latter is without one.) and see it with viewer
  4. click the link you attached.

Expected behavior

expect to move to attached link

Desktop (please complete the following information):

ethanfann commented 1 year ago

This is due to ToastUI editor treating links as relative if they don't explicitly include http(s)://. Workarounds are either a) offer some type of UI/UX to hint that a fully qualified domain is required or b) override the query event to handle link popups and insert http(s):// if not present.

Inspired by the comment https://github.com/nhn/tui.editor/issues/1256#issuecomment-1614408477, you can implement this like so:

const editor = new Editor(...);

editor.eventEmitter.removeEventHandlerWithTypeInfo('query');
editor.eventEmitter.listen('query', (query, payload = {}) => {
    if (query === 'getPopupInitialValues' && payload.popupName === 'link') {
        const range = instance.getSelection();
        const info = instance.getRangeInfoOfNode(Math.floor((range[0] + range[1]) / 2));
        if (info.type === 'link') {
            instance.setSelection(...info.range);
            let link = window.getSelection().getRangeAt(0)
                .commonAncestorContainer.parentElement;
            link = link.closest('a') || link.querySelector('a') || link;
            const linkUrl = link.getAttribute('href');
            return {
                linkUrl:
                    linkUrl.startsWith('https://') ||
                    linkUrl.startsWith('http://')
                        ? linkUrl
                        : 'https://' + linkUrl,
                linkText: link.innerText,
            };
        } else {
            return {
                linkText: instance.getSelectedText(),
            };
        }
    }
});

Demo

https://github.com/nhn/tui.editor/assets/6005240/9e9cd142-081a-4868-a77f-e398ee08aa6e